<?php
// ----------------------------------------------------------------------
// pn-commerce Shopping Cart Solution for PostNuke
// http://pncommerce.de
// http://www.sourceforge.net/projects/pn-commerce/
//
// It is based on PostKart 0.701QA from
//                        Destin LeBlanc [ postkart@zenflesh.com ]
// ----------------------------------------------------------------------
// Source file:  $Source: /cvsroot/pn-commerce/pn-commerce/pnadmin.php,v $
//
// Last changes from:  $Author: landseer $
//
// Revision:           $Revision: 1.268 $
//
// Date of revision    $Date: 2005/08/21 13:28:04 $
//
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------
// Purpose of this file: Displaying a simple shoppingcart on your website
//        Administrative functions
// ----------------------------------------------------------------------

require_once("modules/pncommerce/common.php");

/**
 * Generates a url with the given parameters using the standard
 * pnmodurl and if needed replaces the beginning with https or the sslpath
 * @param $Module string The modulename
 * @param $Section string section like admin or user
 * @param $Function string the function to call
 * @param $Args array the array of arguments for the Function
 * @return string the generated URL
 */
function pncAdminModURL($Module, $Section, $Function, $Args=array())
{
    pncloadapi('user', __FILE__, __LINE__);
    return pnModAPIFunc( 'pncommerce', 'user','pncModURL',
                                 array( 'Module'=>$Module,
                                            'Section'=>$Section,
                                            'Function'=>$Function,
                                            'Args'=>$Args ) );
}

/*
 * main
 * main administration panel
 * does not need any parameter and does not return anything
 */
function pncommerce_admin_main()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::configuration', '::', ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    pnSessionDelVar( 'PNCOrdernumber' );

    // delete former search results now
    pnSessionDelVar( 'PNCAdminItemSearchQuery' );
    pnSessionDelVar( 'PNCAdminCustomerSearchResult' );
    pnSessionDelVar( 'PNCAdminReceiptSearchQuery' );
    // reset flag PNCMD5Servers - we will recheck after entering debuginfo() again
    pnSessionSetVar( 'PNCMD5Servers', false);

    // now scan for the custom modules pncm*'s
    $dir = opendir ( "modules/pncommerce" );
    $count = 0;
    $cms = array();
    while ( $cm = readdir( $dir ) )
    {
        if ( ereg("pncm", $cm) )
        {
            // modifier found
            // remove api.php
            $cm1 = str_replace("api.php", "", $cm);
            // remove leading pn
            $cm1 = substr( $cm1, 2, strlen($cm1) - 2 );
            pncloadapi($cm1, __FILE__, __LINE__);
            $count++;
            $cms[$count]=array(
                 'name'=> $cm1,
                 'info'=> pnModAPIFunc ('pncommerce', $cm1, 'info' ) );
            addlogmessage( _PNC_LOG_DEBUG, "custom module $cm1 added" );
        }
    }
    addlogmessage( _PNC_LOG_DEBUG, "$count custom modules read from filesystem" );

    pnModAPIFunc('pncommerce','user','clearoldcart');
    //$catlist = pnModAPIFunc('pncommerce','user','readCategorylist');
    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    list($cat_list, $num_items) = pnModAPIFunc('pncommerce','admin','categorylist');
    $smarty->assign( 'AvailableCategoryTree', $cat_list );
    $smarty->assign( 'TemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist' ) );
    $smarty->assign( 'ShopStatus', pnModGetVar( 'pncommerce', 'status' ) );
    $smarty->assign( 'CustomModules', $cms );
    $smarty->assign( 'CustomModuleCount', count( $cms ) );
    $smarty->assign('schemes', pnModAPIFunc('pncommerce', 'admin', 'schemeGet'));
    return $smarty->fetch("pncommerce_admin_main.html" );
}

/**
 * config
 * main shop configuration
 *
 **/
function pncommerce_admin_config()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $urls = array();
    if($text=='')$text=pnVarCleanFromInput('text');

    $urls[admin_main] = pncAdminModURL('pncommerce', 'admin', 'main');
    $urls[admin_configresponse] = pncAdminModURL('pncommerce', 'admin', 'configresponse');
    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    $smarty->assign( 'shop_owneremail', pnModGetVar( 'pncommerce', 'Email' ) );
    $smarty->assign( 'urls', $urls );

    //We have to set the fields, to receive the corresponding information
    $supplier=Array();
    $supplier['Company']=' ';
    $supplier['Address1']=' ';
    $supplier['Address2']=' ';
    $supplier['City']=' ';
    $supplier['State']=' ';
    $supplier['Zip']=' ';
    $supplier['Country']=' ';
    $supplier['Phone']=' ';
    $supplier['Fax']=' ';
    $supplier['Web']=' ';
    $supplier['Email']=' ';
    $supplier['Bank']=' ';
    $supplier['Bankcode']=' ';
    $supplier['Account']=' ';
    $supplier['AddressFormat']=' ';
    $supplier['ShopIntroTemplateID']=' ';
    $supplier['DefaultCategoryViewTemplateID']=' ';
    $supplier['DefaultItemViewTemplateID']=' ';
    $supplier['MailTemplateID']=' ';
    $supplier['InternalMailTemplateID']=' ';
    $supplier['InvoiceTemplateID']=' ';
    $supplier['PrintInvoiceTemplateID']=' ';
    $supplier['MaximumCartLifetime']=' ';
    $supplier['MaxItemsToRemember']=' ';
    $supplier['MaximumLogLevel']=' ';
    $supplier['MinimumOrderValue']=' ';
    $supplier['JumpToCartviewAfterAdd']=' ';
    $supplier['VatIncluded']=' ';
    $supplier['UseAuthKeys']=' ';
    $supplier['TaxNumber']=' ';
    $supplier=pnModAPIFunc('pncommerce','admin','getConfigSupplier',$supplier);
    $supplier['CountryList']=split(",", _PNC_COUNTRIES);
    $supplier['JumpToCartviewAfterAddchecked'] = ( $supplier['JumpToCartviewAfterAdd'] ) ? " checked" : "";
    $supplier['VatIncludedChecked'] = ( $supplier['VatIncluded'] ) ? " checked" : "";
    $supplier['useauthkeyschecked'] = ( $supplier['UseAuthKeys'] =='on' ) ? " checked" : "";

    $smarty->assign('shopConfigSupplier', $supplier );
    extract($supplier);

    // build array for loglevels
    $smarty->assign( 'LogLevels', array( _PNC_LOG_DEBUG         => _PNC_LOG_DEBUGTEXT,
                                         _PNC_LOG_USERERROR     => _PNC_LOG_USERERRORTEXT,
                                         _PNC_LOG_ADMINERROR    => _PNC_LOG_ADMINERRORTEXT,
                                         _PNC_LOG_GENERAL       => _PNC_LOG_GENERALTEXT,
                                         _PNC_LOG_USERWARNING   => _PNC_LOG_USERWARNINGTEXT,
                                         _PNC_LOG_ADMINWARNING  => _PNC_LOG_ADMINWARNINGTEXT,
                                         _PNC_LOG_NOTICE        => _PNC_LOG_NOTICETEXT,
                                         _PNC_LOG_NOLOG         => _PNC_LOG_NOLOGTEXT ) );

    $smarty->assign( 'ShopIntroTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 1, 'recentTemplate' => $ShopIntroTemplateID )));
    $smarty->assign( 'CategoryViewTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 2, 'recentTemplate' => $DefaultCategoryViewTemplateID )));
    $smarty->assign( 'ItemViewTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 4, 'recentTemplate' => $DefaultItemViewTemplateID )));
    $smarty->assign( 'CustomerMailTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 5, 'recentTemplate' => $MailTemplateID )));
    $smarty->assign( 'InternalMailTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 5, 'recentTemplate' => $InternalMailTemplateID )));
    $smarty->assign( 'InvoiceTemplateList',pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 9, 'recentTemplate' => $InvoiceTemplateID )));
    $smarty->assign( 'PrintInvoiceTemplateList',pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 9, 'recentTemplate' => $PrintInvoiceTemplateID )));

    $storePolicies=pnModAPIFunc('pncommerce','admin','getConfigStorePolicies');

    if ( $storePolicies['EnablePolicies'] ) { $storePolicies['enablepolicieschecked'] = " CHECKED"; }
    if ( $storePolicies['AgreeToPolicies'] ) { $storePolicies['agreetopolicieschecked'] = " CHECKED"; }
    if ( $storePolicies['AcknowledgeLaw'] ) { $storePolicies['acknowledgelawchecked'] = " CHECKED"; }

    $storePolicies['StorePolicies'] = pnVarPrepForDisplay($storePolicies['StorePolicies']);
    $smarty->assign( 'shopConfigPolicies', $storePolicies );


    $thumbnail = pnModAPIFunc('pncommerce','admin','getConfigThumbnail');

    if ( $thumbnail['TNUploadDisable'] ) { $thumbnail['tnuploadchecked'] = " CHECKED"; }
    if ( $thumbnail['TNIgnoreDisable'] ) { $thumbnail['tnignorechecked'] = " CHECKED"; }
    if ( $thumbnail['TNCreateDisable'] ) { $thumbnail['tncreatechecked'] = " CHECKED"; }
    if ( $thumbnail['UseImageReplacements'] ) { $thumbnail['useimagereplacementschecked'] = " CHECKED"; }
    if ( $thumbnail['TNCreateMethod'] == "im" ) { $thumbnail['tnimchecked'] = " CHECKED"; }
    if ( $thumbnail['TNCreateMethod'] == "gd" ) { $thumbnail['tngdchecked'] = " CHECKED"; }

    $smarty->assign( 'shopConfigThumbnail', $thumbnail);

    $ssl=Array();
    $ssl=pnModAPIFunc('pncommerce','admin','getConfigSSL');
    $smarty->assign( 'ssl', $ssl);

    if($ssl['UseSSL']=='on')
    {
        $ssl['UseSSLCheck']="checked";
    }

    $smarty->assign( 'shopConfigSSL', $ssl );

    $catalog=pnModAPIFunc('pncommerce','admin','getConfigCatalog');
    $catalog['ShowItemOptions']=Array();
    $catalog['ShowItemOptions']['0']=_PNC_ALL;
    $catalog['ShowItemOptions']['5']='5';
    $catalog['ShowItemOptions']['10']='10';
    $catalog['ShowItemOptions']['25']='25';
    $catalog['ShowItemOptions']['50']='50';
    $catalog['ShowItemOptions']['75']='75';
    $catalog['ShowItemOptions']['100']='100';
    $catalog['ShowItemOptions']['200']='200';

    $smarty->assign( 'shopConfigCatalog', $catalog );

    $articles=pnModAPIFunc('pncommerce','admin','getConfigArticles');
    if( $articles['DefaultTaxExempt'] == 'on' )
    {
        $articles['TaxExemptchecked'] = "checked";
    }
    //$WeightUnit is also set here
    $smarty->assign( 'shopConfigArticles', $articles );

    $general=pnModAPIFunc('pncommerce','admin','getConfigGeneral');
    if( $general['DisableIntl'] == 'on' )
    {
        $general['DisableIntlchecked'] = "checked";
    }
    $smarty->assign( 'shopConfigGeneral', $general);

    $smarty->assign( 'USA', _PNC_USA );
    $smarty->assign( 'Canada', _PNC_CANADA );

    return $smarty->fetch( "pncommerce_admin_config.html" );
}

/**
 *
 *
 */
function pncommerce_admin_configresponse()
{
    pncloadapi('admin', __FILE__, __LINE__);

    $authid = pnVarCleanFromInput( 'authid' );
    if( !pnSecConfirmAuthKey( $authid ) )
    {
        return showerrorpage( array( 'text' => ""._PNC_BADAUTHKEY ) );
    }

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    list( $Company, $Address1, $Address2, $City, $State, $Zip, $Country, $AddressFormat,
          $Bank, $Bankcode, $Account,
          $ShopIntroTemplateID, $DefaultCategoryViewTemplateID,
          $DefaultItemViewTemplateID, $MailTemplateID, $InternalMailTemplateID,
          $InvoiceTemplateID, $PrintInvoiceTemplateID,
          $MaximumCartLifetime, $MaximumLogLevel, $MaxItemsToRemember,
          $Phone, $Fax, $Web, $Email, $DisableIntl, $UseSSL, $SSLPath, $NonSSLPath,
          $TNUploadDisable, $TNIgnoreDisable, $TNCreateDisable, $TNCreateMethod,
          $TNIMPath, $TMGDPath, $TNWidth, $TNHeight, $ShowItems,
          $EnablePolicies, $StorePolicies, $AgreeToPolicies, $AcknowledgeLaw, $IndexTemplate,
          $DefaultTaxExempt,$WeightUnit, $MinimumOrderValue, $JumpToCartviewAfterAdd, $VatIncluded, $UseAuthKeys,
          $ItemImageReplacement, $ItemImageTNReplacement, $CategoryImageReplacement,
          $CategoryImageTNReplacement, $UseImageReplacements, $TaxNumber )
        = pnVarCleanFromInput(
            'Company', 'Address1', 'Address2', 'City', 'State', 'Zip', 'Country', 'AddressFormat',
                        'Bank', 'Bankcode', 'Account',
            			'ShopIntroTemplateID', 'DefaultCategoryViewTemplateID',
			            'DefaultItemViewTemplateID', 'MailTemplateID', 'InternalMailTemplateID',
			            'InvoiceTemplateID', 'PrintInvoiceTemplateID',
                        'MaximumCartLifetime', 'MaximumLogLevel', 'MaxItemsToRemember',
                        'Phone', 'Fax', 'Web', 'Email', 'DisableIntl', 'UseSSL', 'SSLPath', 'NonSSLPath',
                        'TNUploadDisable', 'TNIgnoreDisable', 'TNCreateDisable', 'TNCreateMethod',
                        'TNIMPath', 'TMGDPath', 'TNWidth', 'TNHeight', 'ShowItems',
                        'EnablePolicies', 'StorePolicies', 'AgreeToPolicies', 'AcknowledgeLaw', 'IndexTemplate',
                        'DefaultTaxExempt','WeightUnit', 'MinimumOrderValue', 'JumpToCartviewAfterAdd', 'VatIncluded', 'UseAuthKeys',
                        'ItemImageReplacement', 'ItemImageTNReplacement',
                        'CategoryImageReplacement', 'CategoryImageTNReplacement', 'UseImageReplacements', 'TaxNumber' );

    $ssl = Array();
    $ssl['UseSSL']=$UseSSL;
    if(isset($UseSSL)){
	     $ssl['SSLPath']=$SSLPath;
	}
    else
	{
	    $ssl['SSLPath']='';
	}
    $ssl['NonSSLPath']=$NonSSLPath;
    pnModAPIFunc('pncommerce','admin','setConfigSSL',$ssl);

    $policies['StorePolicies']=$StorePolicies;
    $policies['EnablePolicies']=$EnablePolicies;
    $policies['AgreeToPolicies']=$AgreeToPolicies;
    $policies['AcknowledgeLaw']=$AcknowledgeLaw;
    pnModAPIFunc('pncommerce','admin','setConfigStorePolicies',$policies);

    $supplier=Array();
    $supplier['Company']=$Company;
    $supplier['Address1']=$Address1;
    $supplier['Address2']=$Address2;
    $supplier['City']=$City;
    $supplier['State']=$State;
    $supplier['Zip']=$Zip;
    $supplier['Country']=$Country;
    $supplier['Phone']=$Phone;
    $supplier['Fax']=$Fax;
    $supplier['Web']=$Web;
    $supplier['Email']=$Email;
    $supplier['TaxNumber']=$TaxNumber;
    $supplier['Bank']=$Bank;
    $supplier['Bankcode']=$Bankcode;
    $supplier['Account']=$Account;
    $supplier['AddressFormat']=$AddressFormat;
    $supplier['ShopIntroTemplateID']=$ShopIntroTemplateID;
    $supplier['DefaultCategoryViewTemplateID']=$DefaultCategoryViewTemplateID;
    $supplier['DefaultItemListTemplateID']=$DefaultItemListTemplateID;
    $supplier['DefaultItemViewTemplateID']=$DefaultItemViewTemplateID;
    $supplier['MailTemplateID']=$MailTemplateID;
    $supplier['InternalMailTemplateID']=$InternalMailTemplateID;
    $supplier['SearchResultTemplateID']=$SearchResultTemplateID;
    $supplier['HeaderTemplateID']=$HeaderTemplateID;
    $supplier['FooterTemplateID']=$FooterTemplateID;
    $supplier['InvoiceTemplateID']=$InvoiceTemplateID;
    $supplier['PrintInvoiceTemplateID']=$PrintInvoiceTemplateID;
    $supplier['MaximumCartLifetime']=$MaximumCartLifetime;
    $supplier['MaxItemsToRemember']=$MaxItemsToRemember;
    $supplier['MaximumLogLevel']=$MaximumLogLevel;
    $supplier['MinimumOrderValue']=$MinimumOrderValue;
    $supplier['JumpToCartviewAfterAdd']=$JumpToCartviewAfterAdd;
    $supplier['VatIncluded']=$VatIncluded;
    $supplier['UseAuthKeys']=$UseAuthKeys;
    pnModAPIFunc('pncommerce','admin','setConfigSupplier',$supplier);

    $thumbnails=Array();
    $thumbnails['TNUploadDisable']=$TNUploadDisable;
    $thumbnails['TNIgnoreDisable']=$TNIgnoreDisable;
    $thumbnails['TNCreateDisable']=$TNCreateDisable;
    $thumbnails['TNCreateMethod']=$TNCreateMethod;
    $thumbnails['TNIMPath']=$TNIMPath;
    $thumbnails['TNWidth']=$TNWidth;
    $thumbnails['TNHeight']=$TNHeight;
    $thumbnails['UseImageReplacements']=$UseImageReplacements;
    $thumbnails['ItemImageReplacement']=$ItemImageReplacement;
    $thumbnails['ItemImageTNReplacement']=$ItemImageTNReplacement;
    $thumbnails['CategoryImageReplacement']=$CategoryImageReplacement;
    $thumbnails['CategoryImageTNReplacement']=$CategoryImageTNReplacement;
    if( strtolower($thumbnails['UseImageReplacements']) == 'on' )
    {
        if( $thumbnails['ItemImageReplacement'] == '' ) { $thumbnails['ItemImageReplacement'] = 'noimage.gif'; }
        if( $thumbnails['ItemImageTNReplacement'] == '' ) { $thumbnails['ItemImageTNReplacement'] = 'noimage.gif'; }
        if( $thumbnails['CategoryImageReplacement'] == '' ) { $thumbnails['CategoryImageReplacement'] = 'noimage.gif'; }
        if( $thumbnails['CategoryImageTNReplacement'] == '' ) { $thumbnails['CategoryImageTNReplacement'] = 'noimage.gif'; }

    }
    pnModAPIFunc('pncommerce','admin','setConfigThumbnail',$thumbnails);

    $general=Array();
    $general['DisableIntl']=$DisableIntl;
    pnModAPIFunc('pncommerce','admin','setConfigGeneral',$general);

    $articledef=Array();
    $articledef['DefaultTaxExempt']=$DefaultTaxExempt;
    $articledef['WeightUnit']=$WeightUnit;
    pnModAPIFunc('pncommerce','admin','setConfigArticles',$articledef);

    $catalogdef=Array();
    $catalogdef['ShowItems']=$ShowItems;
    pnModAPIFunc('pncommerce','admin','setConfigCatalog',$catalogdef);

    $templates=Array();
    $templates['IndexTemplate']=$IndexTemplate;
    pnModAPIFunc('pncommerce','admin','setConfigTemplate',$templates);

    pnRedirect ( pncAdminModURL('pncommerce', 'admin', 'main') );
    return true;
}

/**
 * localeconfig
 *
 */
function pncommerce_admin_localeconfig()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $submit = pnVarCleanFromInput('submit');
    if(!isset($submit))
    {
        $localesettings = pnModAPIFunc('pncommerce', 'admin', 'getConfigLocale' );
        $pnr =& new pnRender('pncommerce');
        $pnr->caching = false;
        $pnr->assign('localesettings', $localesettings);
        $pnr->assign('currencysymbolarray', array( _PNC_NOCURRENCYSYMBOL,
                                                   _PNC_CURRENCYSYMBOL,
                                                   _PNC_INTERNATIONALCURRENCYSYMBOL ) );
        return $pnr->fetch('pncommerce_admin_locale.html');
    }
    else // submit is set
    {
        $authid = pnVarCleanFromInput( 'authid' );
        if( !pnSecConfirmAuthKey( $authid ) )
        {
            return showerrorpage( array( 'text' => ""._PNC_BADAUTHKEY ) );
        }
        list( $decimaldelimiter, $thousandsseparator, $currencysymbol,
              $intlcurrencysymbol, $defcurrencysymbol, $locale,
              $dateformat, $timeformat ) =
              pnVarCleanFromInput( 'decimaldelimiter', 'thousandsseparator', 'currencysymbol',
                                   'intlcurrencysymbol', 'defcurrencysymbol', 'locale',
                                   'dateformat', 'timeformat' );
        pnModAPIFunc('pncommerce', 'admin', 'setConfigLocale',
                     array( 'Locale'                => $locale,
                            'DateFormat'            => $dateformat,
                            'TimeFormat'            => $timeformat,
                            'DecimalDelimiter'      => $decimaldelimiter,
                            'ThousandsSeparator'    => $thousandsseparator,
                            'CurrencySymbol'        => $currencysymbol,
                            'IntlCurrencySymbol'    => $intlcurrencysymbol,
                            'DefaultCurrencySymbol' => $defcurrencysymbol ));
    }
    pnRedirect ( pncAdminModURL('pncommerce', 'admin', 'main') );
    return true;
}
/**
 * receiptsearch
 *
 */
function pncommerce_admin_receiptsearch()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    list( $criteria, $mode ) = pnVarCleanFromInput( 'criteria', 'mode' );

    $Mn  = date("m");
    $LMn = date("F");
    $Dy  = date("d");
    $Yr  = date("Y");
    $Yr1 = $Yr - 1;
    $Yr2 = $Yr - 2;
    $Yr3 = $Yr - 3;
    $Yr4 = $Yr - 4;
    $Yr5 = $Yr - 5;

    if( $mode == 'showlastresults' )
    {
        // read the previous search results
        $ReceiptSearchQuery = pnSessionGetVar( 'PNCAdminReceiptSearchQuery' );
        if( $ReceiptSearchQuery )
        {
            $smarty =& new pnRender( 'pncommerce' );
            $smarty->caching = false;
            $resultarray = pnModAPIFunc( 'pncommerce', 'admin', 'executeReceiptSearchQuery',
                                         array( 'sql' => $ReceiptSearchQuery ) );
            if( is_array( $resultarray ) )
            {
                $smarty->assign('result',$resultarray);
            }
            else
            {
                $smarty->assign('norecord',true);
            }
            return $smarty->fetch("pncommerce_admin_receiptsearchresult.html" );
        }
        unset( $ReceiptSearchQuery );
    }

    if( !isset($criteria))
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'actYear', $Yr );
        $daylist=array();
        for($i=1;$i<32;$i++) $daylist[]=$i;
        $yearlist=array($Yr1,$Yr2,$Yr3,$Yr4,$Yr5);

        $smarty->assign( 'Day', $Dy );
        $smarty->assign( 'MonSel'.$Mn, 'Selected' );
        $smarty->assign( 'daylist', $daylist );
        $smarty->assign( 'yearlist', $yearlist );

        return $smarty->fetch("pncommerce_admin_receiptsearch.html" );
    }
    else // $criteria is set
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        // These are the fields we are going to read. We store this here once so that we
        // only need to change here and the list() below if more information are needed
        //
        $select = "UserID, OrderNumber, OrderStatus, Date, CartData";
        switch ($criteria)
        {
        case "order":
            $ON = pnVarCleanFromInput('ON');

            list($dbconn, $tablename, $tablecolumn ) = pncOpenDB('pncommerce_orders');

            $sql = "SELECT $tablecolumn[UserID]
                    FROM $tablename
	                WHERE $tablecolumn[OrderNumber]='".(int)$ON."'
	                  AND $tablecolumn[OrderStatus]<99";
            $result = $dbconn->Execute($sql);
            // check for errors or no rows found, and if so return false
            if (($dbconn->ErrorNo() == 0) && (!$result->EOF) )
            {
                list($readkid) = $result->fields;
                pncCloseDB($result);
                pnRedirect ( pncAdminModURL( 'pncommerce', 'user', 'receipt', array('ON' => $ON, 'User' => $readkid, 'Admin'=>true)) );
                return true;
            }
/*
            $sql = "SELECT UserID FROM ".pnConfigGetVar('prefix')."_pncommerce_orders
                    WHERE OrderNumber='$ON' AND OrderStatus<99";
            $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                                    array( 'sql' => $sql ) );
            if ( $result != false )
            {
                pnRedirect ( pncAdminModURL( 'pncommerce', 'user', 'receipt', array('ON' => $ON, 'User' => $result[0][0], 'Admin'=>true)) );
                return true;
            }
*/
            else
            {
                pnSessionSetVar( 'PNCAdminReceiptSearchQuery', $sql );
                $smarty->assign('norecord',true);
                $smarty->assign('query',""._PNC_ORDERNUMBER."= $ON");
                return $smarty->fetch("pncommerce_admin_receiptsearchresult.html" );
            }
            break;
        case "name":
            $User = pnVarCleanFromInput('User');
            $sql = "SELECT $select FROM ".pnConfigGetVar('prefix')."_pncommerce_orders
                    WHERE UserID LIKE '%".pnVarPrepForStore($User)."%' ORDER BY UserID";
               $smarty->assign('query',""._PNC_USER."= $User");
            break;
        case "date":
                    list($Month, $Day, $Year) = pnVarCleanFromInput('Month', 'Day', 'Year');
                    if($Year=="")
                    {
                            $StartDate=0;
                            $EndDate=time();
                            $Year=( _PNC_ANYYEAR." - ");
                            $Month=( _PNC_ANYMONTH." - ");
                            $Day=(_PNC_ANYDAY." - ");
                    }
                    elseif($Month=="" && $Year!="")
                    {
                            $Day=$Month=1;
                            $EDay=31;
                            $EMonth=12;
                            $StartDate=mktime(0, 0, 0, $Month, $Day, $Year);
                            $EndDate=mktime(0, 0, 0, $EMonth, $EDay, $Year);
                            $Month=( _PNC_ANYMONTH." - ");
                            $Day=(_PNC_ANYDAY." - ");
                    }
                    elseif($Day=="" && $Month!="" && $Year!="")
                    {
                            $Day=1;
                            $EDay=31;
                            $StartDate=mktime(0, 0, 0, $Month, $Day, $Year);
                            $EndDate=mktime(0, 0, 0, $Month, $EDay, $Year);
                            $Day=(_PNC_ANYDAY." - ");
                    }
                    else
                    {
                            $StartDate=mktime(0, 0, 0, $Month, $Day, $Year);
                            $EndDate=mktime(0, 0, 0, $Month, ($Day+1), $Year);
                    }
                    $sql = "SELECT $select
                            FROM ".pnConfigGetVar('prefix')."_pncommerce_orders
                            WHERE Date>=$StartDate AND Date<=$EndDate
                            ORDER BY OrderNumber";
               $smarty->assign('query',""._PNC_DATE."=$Year  $Month  $Day ");
            break;
        case "between":
                    list($sm, $sd, $sy, $em, $ed, $ey) = pnVarCleanFromInput('startmonth', 'startday', 'startyear','endmonth', 'endday', 'endyear');
                    $StartDate=mktime(0, 0, 0, $sm, $sd, $sy);
                    $EndDate=mktime(0, 0, 0, $em, ($ed+1), $ey);
                    $sql = "SELECT $select
                            FROM ".pnConfigGetVar('prefix')."_pncommerce_orders
                            WHERE Date>=$StartDate AND Date<=$EndDate ORDER BY OrderNumber";
               $smarty->assign('query',""._PNC_DATE."= $sy-$sm-$sd  ----  $ey-$em-$ed");
            break;
        case "orderstatus":
                    $orderstatus = (int)pnVarCleanFromInput( 'orderstatus' );
                    if( $orderstatus >= 0 )
                    {
                        $sql = "SELECT $select
                                FROM ".pnConfigGetVar('prefix')."_pncommerce_orders
                                WHERE OrderStatus=$orderstatus ORDER BY OrderNumber";
                        $smarty->assign( 'query', ""._PNC_ORDERSTATUS."= $orderstatus" );
                    }
                    else
                    {
                        $sql = "SELECT $select
                                FROM ".pnConfigGetVar('prefix')."_pncommerce_orders
                                WHERE OrderStatus>=0 ORDER BY OrderNumber";
                        $smarty->assign( 'query', ""._PNC_ORDER_ALL );
                    }
                    break;
        default:
            $sql = "";
            $noresult = "";
            break;
        }
        if( $sql )
        {
            $resultarray = pnModAPIFunc( 'pncommerce', 'admin', 'executeReceiptSearchQuery',
                                         array( 'sql' => $sql ) );
            if( is_array( $resultarray ) )
            {
                pnSessionSetVar( 'PNCAdminReceiptSearchQuery', $sql );
                $smarty->assign('result',$resultarray);
            }
            else
            {
                $smarty->assign('norecord',true);
            }
        }
        else
        {
            $smarty->assign('query', ""._PNC_NOQUERY);
            $smarty->assign('norecord',true);
        }
        return $smarty->fetch("pncommerce_admin_receiptsearchresult.html" );
    }
}

/*
 * orderupdate
 *
 */
function pncommerce_admin_orderupdate()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::order', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    list( $KID, $ON, $Update ) = pnVarCleanFromInput( 'KID', 'ON', 'Update' );

    // read the order
    $order = pnModAPIFunc( 'pncommerce', 'user', 'getOrder',
                           array( 'ON'  => $ON,
                                  'KID' => $KID ) );

    if( $order == false)
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( "ResponseText", "<b>"._PNC_ORDER." $ON :"._PNC_NODBDATA."</b>" );
        return $smarty->fetch( 'pncommerce_admin_ordermanagementresponse.html' );
    }

    if ( !$Update )
    {

        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'Order', $order );
        $smarty->assign( 'OrderStatusList', pnModAPIFunc( 'pncommerce', 'admin', 'createOrderStatusListForSelect', array('OrderStatus' => $order['OrderStatus'] ) ) );
        return $smarty->fetch( 'pncommerce_admin_orderupdate.html' );
    }
    else  // $Update is set
    {
        $responsemessage = array();
        // now the real works starts
        if( $order['OrderStatus'] < 90 )
        {
            // save the order remark
            $order['CartData']['Remark'] = pnVarCleanFromInput( 'OrderRemark' );
            $orderstatus = pnVarCleanFromInput( 'OrderStatus' );

            for($count=0;$count<count( $order['CartData']['Items'] );$count++ )
            {
                // process each item
                // read the OQ (ordered quantity), DQ (deliverd quantity) and DONE (position closed)
                list( $deliveredqty, $itemdone ) = pnVarCleanFromInput( 'DQ_'.$count, 'DONE_'.$count );
                // read the item data from the db
                list($IQH, $IIQ, $IQO) = pnModAPIFunc ( 'pncommerce', 'user', 'readfromDB', array ('table' => 'items',  'required' => array ('ItemID', $order['CartData']['Items'][$count]['ItemID']), 'fields' => array ('ItemQuantity', 'IgnoreQuantity', 'QuantityOrdered')));
                // set the remark
                $order['CartData']['Items'][$count]['ItemRemark'] = pnVarCleanFromInput( 'REM_'.$count );

                if( $IIQ != "on" )
                {
                    // we do not ignore the item quantity
                    // update QuantityOrdered
                    $IQO = $IQO + $order['CartData']['Items'][$count]['ItemDelQty'] - $deliveredqty;
                    // update ItemQuantity (the stock - if we delivered something it has to be deducted here
                    $IQH = $IQH + $order['CartData']['Items'][$count]['ItemDelQty'] - $deliveredqty;
                    // update the IQO and IQH in the items table
                    pnModAPIFunc( 'pncommerce', 'user', 'executesqlDB',
                                            array( 'sql' => "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_items
                                                                                    SET ItemQuantity=".pnVarPrepForStore($IQH).", QuantityOrdered=".pnVarPrepForStore($IQO)."
                                                                                    WHERE ItemID='".(int)$order['CartData']['Items'][$count][ItemID]."'"));
                }
                $order['CartData']['Items'][$count]['ItemDelQty'] = $deliveredqty;
                $order['CartData']['Items'][$count]['ItemDone'] = $itemdone;

                // we $count from 0 to ..., but in the display, we show 1 to ....
                // so we need a disp_count variable here
                $disp_count = $count + 1;
                $remainingqty = $order['CartData']['Items'][$count]['ItemQuantity'] - $deliveredqty;
                $responsemessagetemp = "<div align='center'><font class=\"pn-normal\"><b>"._PNC_ORDERNUMBER." $ON, "._PNC_ITEM." $disp_count "._PNC_CHANGED." ("._PNC_REMAININGQTY.":".$remainingqty;
                if ($itemdone==true)
                {
                    $responsemessagetemp .= " -- "._PNC_ITEMCLOSED;
                }
                else
                {
                    if( $remainingqty==0 )
                    {
                        $locagain  = pncAdminModURL( 'pncommerce', 'admin', 'orderupdate', array( 'ON' => $ON, 'KID' => $KID ) );
                        $responsemessagetemp .= "<br><b><a href=\"$locagain\">"._PNC_ITEMCANBECLOSED."</a></b>";
                    }
                }
                $responsemessagetemp .=")</div><br>";
                $responsemessage[] = $responsemessagetemp;
                unset($responsemessagetemp);
            } // for
            // update cartdata in the order
            pnModAPIFunc( 'pncommerce', 'user', 'executesqlDB',
                          array( 'sql' => "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_orders
                                 SET OrderStatus = ".(int)$orderstatus.", CartData = '".addslashes( serialize( $order['CartData'] ) )."', lastChange = '".time()."' WHERE OrderNumber='".(int)$ON."'"));
        }
        else
        {
            // orderstatus >= 90
            $responsemessage[] = "<p align='center'><font class=\"pn-normal\"><b>"._PNC_ORDER." $ON "._PNC_COULDNOTBECHANGED." ("._PNC_ORDERSTATUS.": ".$order['OrderStatus'].")</p><br>";
        }
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'OrderNumber', $ON );
        $smarty->assign( 'CustomerID', $KID );
        $smarty->assign( 'ResponseMessages', $responsemessage );
        return $smarty->fetch( 'pncommerce_admin_orderupdateresponse.html' );
    }
}


/**
 * orderdelete
 *
 */

function pncommerce_admin_orderdelete()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::order', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    list($ON, $KID, $Submit, $Delete) = pnVarCleanFromInput('ON', 'KID', 'Submit', 'Delete');

    if (!$Delete)
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'OrderNumber', $ON );
        $smarty->assign( 'CustomerID', $KID );
        return $smarty->fetch( 'pncommerce_admin_orderdelete.html' );
    }
    else
    {
        // start the deleting of order $ON
        // read the order information
        $order = pnModAPIFunc( 'pncommerce', 'user', 'getOrder',
                               array( 'ON' => $ON ) );

        if($order==false)
        {
            // no order - should not happen
            return showerrorpage(_PNC_NODBDATA, __FILE__, __LINE__);
        }
        // visit every item in the order
        // we need to update the QuantityOrdered in the item which means we have to
        // reduce the QuantityOrderedd by the qty in the order if the order has not been fulfilled

        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;

        if( $order['OrderStatus'] < 90 )
        {
            foreach( $order['CartData']['Items'] as $cartitem )
            {
                // get ItemQuantity, IgnoreQuantity and OrderedQuantity for this item
                list($IQH, $IIQ, $IQO) = pnModAPIFunc ( 'pncommerce', 'user', 'readfromDB', array ('table' => 'items',  'required' => array ('ItemID', $cartitem['ItemID']), 'fields' => array ('ItemQuantity', 'IgnoreQuantity', 'QuantityOrdered')));
                if( $IIQ != "on" )
                {
                    // we do not ignore the item quantity
                    $IQO = $IQO - $cartitem['ItemQuantity'];
                    // update the IQO in the items table
                    pnModAPIFunc( 'pncommerce', 'user', 'executesqlDB',
                                  array('sql' => "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_items SET QuantityOrdered='".pnVarPrepForStore($IQO)."' WHERE ItemID='".(int)$cartitem['ItemID']."'"));
                }
            }
            $sql = "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_orders SET OrderStatus = 99, lastChange = '".time()."' WHERE OrderNumber='".(int)$ON."'";
            pnModAPIFunc( 'pncommerce', 'user', 'executesqlDB',
                          array( 'sql' => $sql ));
            $smarty->assign( "ResponseText", ""._PNC_ORDER." #$ON "._PNC_HASBEENDELETED );
        }
        else
        {
            // orderstatus >= 90, either fulfilled or already deleted
            $smarty->assign( "ResponseText", ""._PNC_ORDERCOULDNOTBEDELETED." ("._PNC_ORDERSTATUS." = ".$order['OrderStatus'].")" );
        }
        return $smarty->fetch( 'pncommerce_admin_ordermanagementresponse.html' );

    }
}

/////////////////////////////////////////////////
function pncommerce_admin_categoryedit()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    list( $Mode, $CID ) = pnVarCleanFrominput( 'Mode', 'CID' );
    $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$CID));
    if (!pnSecAuthAction(0, 'pncommerce::category', '$CName::$CID', ACCESS_EDIT))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    switch( $Mode )
    {
        case 'add':
                // create an "new category" array
                $smarty->assign( 'CategoryViewTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 2, 'recentTemplate' => 0 ) ) );
                $smarty->assign( 'ItemViewTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 4, 'recentTemplate' => 0 ) ) );
                $cat = pnModAPIFunc( 'pncommerce', 'user', 'getCategory', array( 'CategoryID' => -1 ) );
                $smarty->assign( 'Category', $cat );
                break;
        case 'edit':
                $cat = pnModAPIFunc( 'pncommerce', 'user', 'getCategory', array( 'CategoryID' => $CID ) );
                $smarty->assign( 'CategoryViewTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 2, 'recentTemplate' => $cat['CategoryViewTemplateID'] ) ) );
                $smarty->assign( 'ItemViewTemplateList', pnModAPIFunc( 'pncommerce', 'admin', 'readtemplatelist', array( 'TypeOnly' => 4, 'recentTemplate' => $cat['ItemViewTemplateID'] ) ) );
                $smarty->assign( 'Category', $cat );
                break;
        default:
                break;
    }
    list($cat_list, $num_items) = pnModAPIFunc('pncommerce','admin','categorylist',
                                               array( 'selected' => $cat['ParentID'],
                                                      'NoParentCategoryOption' => true ) );
    $smarty->assign( 'AvailableCategoryTree', $cat_list );
    $smarty->assign( 'ImageDirIsWritable', is_writable( 'modules/pncommerce/category_images') );
    if( $cat['TrueVatID'] == true )
    {
        $smarty->assign( 'VATList', pnModAPIFunc( 'pncommerce', 'admin', 'readVATList', array( 'recentVATID' => $cat['VatID'] ) ) );
    }
    else
    {
        $smarty->assign( 'VATList', pnModAPIFunc( 'pncommerce', 'admin', 'readVATList', array( 'recentVATID' => 0 ) ) );
    }
//echo "<pre>";
//print_r($cat);
//echo "</pre>";
    return $smarty->fetch( 'pncommerce_admin_categoryedit.html' );
}

/*
 * categoryeditresponse
 *
 */
function pncommerce_admin_categoryeditresponse()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    $authid = pnVarCleanFromInput( 'authid' );
    if( !pnSecConfirmAuthKey( $authid ) )
    {
        return showerrorpage( array( 'text' => ""._PNC_BADAUTHKEY ) );
    }

    global $HTTP_POST_FILES;

    list($Cat, $CID, $CSeq, $CPa, $CInv, $VatID, $CIntroID, $IViewID, $tngen, $delimagetn, $delimage, $redirect) =
    pnVarCleanFromInput('Category', 'CID', 'CSeq', 'CPa', 'CatInvisible',
                        'VatID', 'CatIntroTemplateID', 'ItemViewTemplateID','tngen',
                        'delimagetn', 'delimage', 'redirect');

    if( $CID>=0 )
    {
        $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$CID));
        if (!pnSecAuthAction(0, 'pncommerce::category', '$CName::$CID', ACCESS_EDIT))
        {
            return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
        }
/*  We have to check for the old name here!
      if (!pnSecAuthAction(0, 'pncommerce::category', '$Cat::$CID', ACCESS_EDIT))
                {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
        }
  */
    }
    else
    {
        if (!pnSecAuthAction(0, 'pncommerce::category', '$Cat::$CID', ACCESS_ADD))
        {
            return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
        }
    }
    // Category input validation
    $validargs['Category']=$Cat;
    $validargs['CategoryID']=$CID;
    $validargs['CategorySequence']=$CSeq;
    $validargs['CategoryParent']=$CPa;
    $validargs['CategoryInvisible']=$CInv;
    $validargs['VATID']=$VatID;
    $validargs['CatIntroTemplateID']=$CIntroID;
    $validargs['ItemViewTemplateID']=$IViewID;
    $validresult = pnModAPIFunc('pncommerce','admin','CategoryValid',$validargs);
    if( is_array($validresult) )
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'ErrorMsg', $validresult );
        return $smarty->fetch( 'pncommerce_admin_showerrormessages.html' );
    }

    //Now the  images
    // image variable prep
    $Thumbnails=pnModAPIFunc('pncommerce','admin','getConfigThumbnail');
    extract($Thumbnails);

    $image = $_FILES['image'];
    $image_size = $_FILES['image']['size'];
    $image_type = $_FILES['image']['type'];
    $image_tmpname = $_FILES['image']['tmp_name'];
    $image_name = $_FILES['image']['name'];

    $imagetn = $_FILES['imagetn'];
    $imagetn_size = $_FILES['imagetn']['size'];
    $imagetn_type = $_FILES['imagetn']['type'];
    $imagetn_tmpname = $_FILES['imagetn']['tmp_name'];
    $imagetn_name = $_FILES['imagetn']['name'];

    $imagedir = "modules/pncommerce/category_images";
    $imagefile = pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $CID,  'imagefolder'=>'category_images')) ;
    $imagetnfile = pnModAPIFunc('pncommerce','user','getImageName', array('ItemSKU' => $CID, 'thumbnail'=>true, 'imagefolder'=>'category_images')) ;
    // Image file validation
    if ( $image_name != "" )$validargs['image']=$_FILES['image'];
    if ( $imagetn_name != "" )$validargs['imagetn']=$_FILES['imagetn'];
    if ( $imagetn_name != "" )$validargs['image_fname']=$imagefile;
    $validresult=pnModAPIFunc('pncommerce','admin','ArticleImagesValid',$validargs);
    if( is_array($validresult) )
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'ErrorMsg', $validresult );
        return $smarty->fetch( 'pncommerce_admin_showerrormessages.html' );
    }

    $imgdelargs=Array();
    $imgdelargs['itemID']=$CID;
    $imgdelargs['delimage']=$delimage;
    $imgdelargs['delimagetn']=$delimagetn;
    $imgdelargs['imagefolder']='category_images';
    pnModAPIFunc('pncommerce','admin','ArticleImagesRemove',$imgdelargs);

    list($tnwidth, $tnheight) = pnVarCleanFromInput('tnwidth', 'tnheight');

    if(($image_name!="")||($imagetn_name!="")||(($tngen=='create')&&file_exists($imagefile)))
    {
        // upload image & upload/create/ignore TN
        $imgargs=Array();
        $imgargs['itemID']=$CID;
        $imgargs['image']=$image;
        $imgargs['imagefolder']='category_images';
        if(($tngen == 'upload') && ($imagetn_name != ""))$imgargs['imagetn']=$imagetn;
        if($tngen=='create')
        {
            $imgargs['tnwidth']=$tnwidth;
            $imgargs['tnheight']=$tnheight;
        }
        pnModAPIFunc('pncommerce','admin','ArticleImagesStore',$imgargs);
    }

    //save
    if ( $CID>=0 )
    {
        // if this is an existing Category being edited
        pnModAPIFunc('pncommerce','admin','CategoryStore',
                     array( 'Category'           =>$Cat,
                            'CategoryID'         =>$CID,
                            'CategorySequence'   =>$CSeq,
                            'CategoryParent'     =>$CPa,
                            'CategoryInvisible'  =>$CInv,
                            'VATID'              =>$VatID,
                            'CatIntroTemplateID' =>$CIntroID,
                            'ItemViewTemplateID' =>$IViewID));
    }
    else
    {
        $result=pnModAPIFunc('pncommerce','admin','CategoryAdd',
                              array( 'Category'           =>$Cat,
                                     'CategorySequence'   =>$CSeq,
                                     'CategoryParent'     =>$CPa,
                                     'CategoryInvisible'  =>$CInv,
                                     'VATID'              =>$VatID,
                                     'CatIntroTemplateID' =>$CIntroID,
                                     'ItemViewTemplateID' =>$IViewID ) );
        $CID=$result['CategoryID'];
    }

    // lets see where the admin wants us to go now
    switch( $redirect )
    {
        case 'backtocategory':
                $redirect_to = pncAdminModURL( 'pncommerce', 'admin', 'categoryedit',
                                               array( 'CID' => $CID,
                                                      'Mode' => 'edit' ) );
                break;
        case 'backtotree':
                $redirect_to = pncAdminModURL( 'pncommerce', 'admin', 'structuretree',
                                               array( 'open' => '',
                                                      'showCat' => $CID ) );
                break;
        case 'backtomain':
        default:
                $redirect_to = pncAdminModURL( 'pncommerce', 'admin', 'main' );
    }
    pnRedirect( $redirect_to );
    return true;


}

/*
 * itemedit
 *
 */
function pncommerce_admin_itemedit()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    list( $Mode, $IID, $SKU, $Referer ) = pnVarCleanFromInput( 'Mode', 'IID', 'SKU', 'Referer' );

    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;

    switch( $Mode )
    {
        case 'add':
                $item = pnModAPIFunc( 'pncommerce', 'user', 'getItem', array( 'ItemID' => -1 ) );
                if (!pnSecAuthAction(0, 'pncommerce::category', $item['Category'].'::'.$item['CategoryID'], ACCESS_ADD))
                {
                    return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
                }
                $smarty->assign( 'Item', $item );
                $smarty->assign( 'AvailableCategories', pnModAPIFunc( 'pncommerce', 'admin', 'readAllCategoriesForSelect', array( 'SelectedCategory' => 0 ) ) );
                break;
        case 'edit':
                if(!empty($IID)) {
                    $item = pnModAPIFunc( 'pncommerce', 'user', 'getItem', array( 'showhidden'=>true,'ItemID' => $IID ) );
                } else {
                    $item = pnModAPIFunc( 'pncommerce', 'user', 'getItem', array( 'showhidden'=>true,'ItemSKU' => $SKU ) );
                }
                if (!(pnSecAuthAction(0, 'pncommerce::category', $item['Category'].'::'.$item['CategoryID'], ACCESS_EDIT)
                    &&pnSecAuthAction(0, 'pncommerce::item', $item['SKU'].'::'.$item['ID'], ACCESS_EDIT)))
                {
                    return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
                }
                $smarty->assign( 'Item', $item );
                $smarty->assign( 'AvailableCategories', pnModAPIFunc( 'pncommerce', 'admin', 'readAllCategoriesForSelect', array( 'SelectedCategory' => $item['CategoryID']) ) );
                break;
        default:
                break;
    }
    list($cat_list, $num_items) = pnModAPIFunc('pncommerce','admin','categorylist', array('selected' =>$item['CategoryID']));
     $smarty->assign( 'AvailableCategoryTree', "$cat_list" );
    $smarty->assign('suppliers', pnModAPIFunc('pncommerce', 'admin', 'supplierGet'));

    $smarty->assign( 'ImageDirIsWritable', is_writable( 'modules/pncommerce/product_images') );

    if( $item['TrueVatID'] == true )
    {
        $smarty->assign( 'VATList', pnModAPIFunc( 'pncommerce', 'admin', 'readVATList', array( 'recentVATID' => $item['VatID'] ) ) );
    }
    else
    {
        $smarty->assign( 'VATList', pnModAPIFunc( 'pncommerce', 'admin', 'readVATList', array( 'recentVATID' => 0 ) ) );
    }

    return $smarty->fetch( 'pncommerce_admin_itemedit.html' );


}

/*
 * itemeditresponse
 *
 */
function pncommerce_admin_itemeditresponse()
{
    pncloadapi('admin', __FILE__, __LINE__);

    global $HTTP_POST_FILES;
    list( $oldscheme_id,$scheme_id, $supplier_id, $ItemSKU, $ItemName, $ItemDescription, $ItemCost, $Weight, $CategoryID,
          $ItemQuantity, $IgnoreQuantity, $IID, $tngen, $TaxExempt, $delimagetn, $delimage, $VATID, $redirect) =
            pnVarCleanFromInput('oldScheme_ID','Scheme_ID', 'Supplier_ID', 'ItemSKU', 'ItemName', 'ItemDescription', 'ItemCost','Weight',
                                'CategoryID', 'QuantityOnHand', 'IgnoreQuantity', 'ItemID', 'tngen',
                                'TaxExempt', 'delimagetn', 'delimage', 'VATID', 'redirect');

    $authid = pnVarCleanFromInput( 'authid' );
/*    if( !pnSecConfirmAuthKey( $authid ) )
    {
        return showerrorpage( array( 'text' => ""._PNC_BADAUTHKEY ) );
    }
*/
    if ( $IID > 0 )
    {
         $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$CategoryID));
         if (!(pnSecAuthAction(0, 'pncommerce::category', $CName."::".$CategoryID, ACCESS_EDIT)
           &&pnSecAuthAction(0, 'pncommerce::item', $CName."::".$CategoryID, ACCESS_EDIT)))
         {
            return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
        }
    }
    else
    {
        $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$CategoryID));
        if (!(pnSecAuthAction(0, 'pncommerce::category', $CName."::".$CategoryID, ACCESS_ADD)
          &&pnSecAuthAction(0, 'pncommerce::item', $CName."::".$CategoryID, ACCESS_ADD)))
        {
            return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
        }
    }

    $ItemCost = pnModAPIFunc('pncommerce', 'admin', 'convertToNumber', array('value' => $ItemCost));
    $Weight = pnModAPIFunc('pncommerce', 'admin', 'convertToNumber', array('value' => $Weight));
    $ItemSKU = ereg_replace( "[\/]", "", $ItemSKU);
    $ItemName = trim($ItemName);
    $ItemDescription = trim($ItemDescription);

    $args['ItemID']=$IID;
    $args['ItemSKU']=$ItemSKU;
    $args['ItemCost']=$ItemCost;
    $args['VATID']=$VATID;
    $args['Weight']=$Weight;
    $args['CategoryID']=$CategoryID;
    $args['ItemName']=$ItemName;

    $validresult=pnModAPIFunc('pncommerce','admin','ArticleValid',$args);
    if( is_array($validresult) )
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'ErrorMsg', $validresult );
        return $smarty->fetch( 'pncommerce_admin_showerrormessages.html' );
    }

    // image variable prep
    $Thumbnails=pnModAPIFunc('pncommerce','admin','getConfigThumbnail');
    extract($Thumbnails);

    $image = $_FILES['image'];
    $image_size = $_FILES['image']['size'];
    $image_type = $_FILES['image']['type'];
    $image_tmpname = $_FILES['image']['tmp_name'];
    $image_name = $_FILES['image']['name'];

    $imagetn = $_FILES['imagetn'];
    $imagetn_size = $_FILES['imagetn']['size'];
    $imagetn_type = $_FILES['imagetn']['type'];
    $imagetn_tmpname = $_FILES['imagetn']['tmp_name'];
    $imagetn_name = $_FILES['imagetn']['name'];

    $imagedir = "modules/pncommerce/product_images";
    $imagefile = pnModAPIFunc('pncommerce','user','getImageName', array('ItemID' => $ItemSKU)) ;
    $imagetnfile = pnModAPIFunc('pncommerce','user','getImageName', array('ItemID' => $ItemSKU, 'thumbnail'=>true)) ;

    // Image file validation
    if ( $image_name != "" )$validargs['image']=$_FILES['image'];
    if ( $imagetn_name != "" )$validargs['imagetn']=$_FILES['imagetn'];
    if ( $imagetn_name != "" )$validargs['image_fname']=$imagefile;
    $validresult=pnModAPIFunc('pncommerce','admin','ArticleImagesValid',$validargs);
    if( is_array($validresult) )
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'ErrorMsg', $validresult );
        return $smarty->fetch( 'pncommerce_admin_showerrormessages.html' );
    }

    $imgdelargs=Array();
    $imgdelargs['itemID']=$ItemSKU;//This is only used for the name, there are no DB calls made with this parameter
    $imgdelargs['delimage']=$delimage;
    $imgdelargs['delimagetn']=$delimagetn;
    pnModAPIFunc('pncommerce','admin','ArticleImagesRemove',$imgdelargs);

    list($tnwidth, $tnheight) = pnVarCleanFromInput('tnwidth', 'tnheight');

    if(($image_name!="")||($imagetn_name!="")||(($tngen=='create')&&file_exists($imagefile)))
    {
        // else upload image & upload/create/ignore TN
        $imgargs=Array();
        $imgargs['itemID']=$ItemSKU;//This is only used for the name, there are no DB calls made with this parameter
        $imgargs['image']=$image;
        if(($tngen == 'upload') && ($imagetn_name != ""))$imgargs['imagetn']=$imagetn;
        if($tngen=='create')
        {
            $imgargs['tnwidth']=$tnwidth;
            $imgargs['tnheight']=$tnheight;
        }
        pnModAPIFunc('pncommerce','admin','ArticleImagesStore',$imgargs);
    }

    // Store the item details
    $arg=Array();
    $arg['ItemSKU']=$ItemSKU;
    $arg['Scheme_ID']=$scheme_id;
    $arg['oldScheme_ID']=$oldscheme_id;
    $arg['ItemName']=$ItemName;
    $arg['ItemDescription']=$ItemDescription;
    $arg['ItemCost']=$ItemCost;
    $arg['VATID']=$VATID;
    $arg['Weight']=$Weight;
    $arg['CategoryID']=$CategoryID;
    $arg['QuantityOnHand']=$ItemQuantity;
    $arg['IgnoreQuantity']=$IgnoreQuantity;
    $arg['TaxExempt']=$TaxExempt;


    if ( $IID > 0 )
    {
        $arg['ItemID']=$IID;
        $props=pnModAPIFunc( 'pncommerce', 'user', 'getPropertiesByID', array( 'object_id' => $IID,'object_type'=> PNC_ITEMPROP ) );
        if(!empty($props)){
            foreach($props as $prop)
            {
                pncloadapi($prop['type'], __FILE__, __LINE__);
                $arg['PropertiesData'][$prop['propertydata_id']]=$prop;
                $arg=pnModAPIFunc( 'pncommerce', $prop['type'], 'processForm', array('object'=>$arg,'property'=>$prop,'purpose'=>'objectedit'));
    //We should add a switch here if we are in edit mode. We can remove the longextfield here for example

            }
        }
        if(!pnModAPIFunc('pncommerce','admin','ArticleStore',$arg))return false;
    }
    else
    {
        $AddResult = pnModAPIFunc('pncommerce','admin','ArticleAdd',$arg);
        $IID=$AddResult['ItemID'];
    }

    // lets see where the admin wants us to go now
    switch( $redirect )
    {
        case 'backtoitem':
                $redirect_to = pncAdminModURL( 'pncommerce', 'admin', 'itemedit',
                                               array( 'IID' => $IID,
                                                      'Mode' => 'edit' ) );
                break;
        case 'backtoitemview':
                $redirect_to = pncAdminModURL( 'pncommerce', 'user', 'itemview',
                                               array( 'ItemID' => $IID ) );
                break;
        case 'backtosearch':
                $redirect_to = pncAdminModURL( 'pncommerce', 'admin', 'itemsearch' );
                break;
        case 'backtotree':
                $redirect_to = pncAdminModURL( 'pncommerce', 'admin', 'structuretree',
                                               array( 'open' => '',
                                                      'showCat' => $CategoryID ) );
                break;
        case 'backtomain':
        default:
                $redirect_to = pncAdminModURL( 'pncommerce', 'admin', 'main' );
    }
    pnRedirect( $redirect_to );
    return true;
}


/////////////////////////////////////////////////
function pncommerce_admin_categoryrem()
{
    pncloadapi('admin', __FILE__, __LINE__);

    $CID = pnVarCleanFromInput('CategoryID');
    $CName=pnModAPIFunc( 'pncommerce', 'user','GetCategoryName',array('CategoryID'=>$CID));
    if (!pnSecAuthAction(0, 'pncommerce::category', $CName."::".$CID, ACCESS_DELETE))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    $result=pnModAPIFunc( 'pncommerce', 'admin', 'CategoryDelete', array( 'CategoryID' => $CID));
    if($result!=true)
    {
        return false;
    }

    pnRedirect( pncAdminModURL( 'pncommerce', 'admin', 'main') );
    return true;
}

/*
 * itemrem
 *
 */
function pncommerce_admin_itemrem()
{
    pncloadapi('admin', __FILE__, __LINE__);

    $IID = pnVarCleanFromInput('ItemID');
    $args=Array();
    $args['ItemID']=$IID;
    $item=pnModAPIFunc( 'pncommerce', 'user','getItem',array('ItemID'=>$IID));
    if (!(pnSecAuthAction(0, 'pncommerce::item', $item['SKU']."::".$item['ID'], ACCESS_DELETE)
      &&pnSecAuthAction(0, 'pncommerce::category', $item['Category']."::".$item['CategoryID'], ACCESS_DELETE)))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    if( pnModAPIFunc('pncommerce','admin','ArticleDelete',$args) == true )
    {
        pnSessionSetVar( "statusmsg", ""._PNC_ITEMDELETED." (ID=$IID)" );
    }
    else
    {
        pnSessionSetVar( "statusmsg", ""._PNC_ITEMNOTDELETED." (ID=$IID)" );
    }

    pnRedirect( pncAdminModURL('pncommerce', 'admin', 'main') );
    return true;
}

/**
 * Paymethodconfig
 */
function pncommerce_admin_paymethodconfig($args)
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::method', 'pm::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $Submit = pnVarCleanFromInput( 'Submit' );
    if( !$Submit )
    {
        $dir = opendir ( "modules/pncommerce" );
        // read the default PM that is to be used for new customers
        $defaultpm = pnModGetVar( 'pncommerce', 'DefaultPM' );
        $pms=array();
        $activepms=array();
        while ( $pm = readdir( $dir ) )
        {
            if ( ereg("pnpm", $pm) )
            {
                // paymethod found
                // remove api.php
                $pm1 = str_replace("api.php", "", $pm);
                // remove leading pn
                $pm1 = substr( $pm1, 2, strlen($pm1) - 2 );
                if (pnSecAuthAction(0, 'pncommerce::method', 'pm::'.$pm1, ACCESS_ADMIN)) {
                    pncloadapi($pm1, __FILE__, __LINE__);
                    $mode = pnModGetVar ('pncommerce', $pm1);

                    $pms[$pm1]=array(
                         'info'=> pnModAPIFunc ('pncommerce', $pm1, 'info' ),
                         'mode'=> $mode );

                    if ( $mode == 'on' )
                    {
                        $pms[$pm1]['state']=""._PNC_ACTIVE;

                        if( $pm1 == "pmgeneric" )
                        {
                            $generics = pnModAPIFunc( 'pncommerce', $pm1, 'getGenericPayMethodNames' );
                            foreach( $generics as $generic )
                            {
                                $activepms[ "pmgeneric_".$generic['name']] = $generic['Description'];
                            }
                        }
                        else
                        {
                            $activepms[$pm1]=$pms[$pm1]['info'];
                        }
                    }
                    else if ( $mode == 'off' )
                    {
                       $pms[$pm1]['state']=""._PNC_INACTIVE;
                    }
                    else
                    {
                        $pms[$pm1]['state']=""._PNC_NOTINSTALLED   ;
                    }
                }
            }
        }
        $urls = array();
        $urls['admin_methodforward'] = pncAdminModURL('pncommerce', 'user', 'MethodForward');
        $urls['admin_main'] = pncAdminModURL('pncommerce', 'admin', 'main');
        $urls['admin_methodconfig'] = pncAdminModURL('pncommerce', 'admin', 'paymethodconfig');
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'urls', $urls );
        $smarty->assign( 'methods', $pms );
        $smarty->assign( 'activems', $activepms );
//        $smarty->assign( 'type', 'pm' );
        $smarty->assign( 'defaultmethod', $defaultpm );
        return $smarty->fetch( "pncommerce_admin_pmmethodconfig.html" );

    } // $Submit is set
    else
    {
        pnModSetVar( 'pncommerce', 'DefaultPM', pnVarCleanFromInput( 'defaultmethod' ) );
            pnRedirect( pncAdminModURL('pncommerce', 'admin', 'paymethodconfig' ) );
        return true;
    }
}

function pncommerce_admin_shippingmethodconfig($args)
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::method', 'sm::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $Submit = pnVarCleanFromInput( 'Submit' );
    if( !$Submit )
    {
        $dir = opendir ( "modules/pncommerce" );
        // read the default PM that is to be used for new customers
        $defaultsm = pnModGetVar( 'pncommerce', 'DefaultSM' );
        $sms=array();
        $activesms=array();
        while ( $sm = readdir( $dir ) )
        {
            if ( ereg("pnsm", $sm) )
            {
                // method found
                // remove api.php
                $sm1 = str_replace("api.php", "", $sm);
                // remove leading pn
                $sm1 = substr( $sm1, 2, strlen($sm1) - 2 );
                if(pnSecAuthAction(0, 'pncommerce::method', 'sm::'.$sm1, ACCESS_ADMIN)) {
                    pncloadapi($sm1, __FILE__, __LINE__);
                    $mode = pnModGetVar ('pncommerce', $sm1);
                    $sms[$sm1]=array(
                        'info'=>pnModAPIFunc ('pncommerce', $sm1, 'info'),
                        'mode'=>pnModGetVar ('pncommerce', $sm1) );
                    if ( $mode == 'on' )
                    {
                        $sms[$sm1]['state']=""._PNC_ACTIVE;
                        if( $sm1 == "smgeneric" )
                        {
                            $generics = pnModAPIFunc( 'pncommerce', $sm1, 'getGenericShippingmethodNames' );
                            foreach( $generics as $generic )
                            {
                                $activesms[ "smgeneric_".$generic['name']] = $generic['Description'];
                            }
                        }
                        else
                        {
                            $activesms[$sm1]=$sms[$sm1]['info'];
                        }
                    }
                    else if ( $mode == 'off' )
                    {
                        $sms[$sm1]['state']=""._PNC_INACTIVE;
                    }
                    else
                    {
                        $sms[$sm1]['state']=""._PNC_NOTINSTALLED   ;
                    }
                }
            }
        }
        $urls = array();
        $urls['admin_methodforward'] = pncAdminModURL('pncommerce', 'user', 'MethodForward');
        $urls['admin_main'] = pncAdminModURL('pncommerce', 'admin', 'main');
        $urls['admin_methodconfig'] = pncAdminModURL('pncommerce', 'admin', 'shippingmethodconfig');
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign( 'urls', $urls );
        $smarty->assign( 'methods', $sms );
        $smarty->assign( 'activems', $activesms );
        $smarty->assign( 'type', 'sm' );
        $smarty->assign( 'defaultmethod', $defaultsm );
        return $smarty->fetch( "pncommerce_admin_smmethodconfig.html" );

    } // $Submit is set
    else
    {
        pnModSetVar( 'pncommerce', 'DefaultSM', pnVarCleanFromInput( 'defaultmethod' ) );
        pnRedirect( pncAdminModURL('pncommerce', 'admin', 'shippingmethodconfig' ) );
        return true;
    }
}

/**
 * TemplateEdit
 *
 **/
function pncommerce_admin_TemplateEdit()
{
    list($TemplateID, $Submit) = pnVarCleanFromInput ('TemplateID', 'Submit' );

    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if(!pnSecAuthAction(0, 'pncommerce::template', $TemplateID.'::', ACCESS_EDIT)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    if(!$Submit) {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $smarty->assign('TemplateList', array("1" => _PNC_TEMPLATETYPE_1,
                                              "2" => _PNC_TEMPLATETYPE_2,
                                              "4" => _PNC_TEMPLATETYPE_4,
                                              "5" => _PNC_TEMPLATETYPE_5,
                                              "9" => _PNC_TEMPLATETYPE_9,
                                              "10" => _PNC_TEMPLATETYPE_10));
        if($TemplateID==-1) {
            // new template
            $Template['ID']   = -1;
            $Template['Type'] = 2;
            $Template['Desc'] = pnVarPrepForDisplay (_PNC_NEWTEMPLATE);
            $Template['Text'] = pnVarPrepForDisplay (_PNC_NEWTEMPLATEFILENAME);
        } else {
            $result = pnModAPIFunc('pncommerce', 'user', 'readfromDBpreformat',
                                    array('sql' => "SELECT TemplateType, TemplateText, TemplateDesc FROM ".pnConfigGetVar('prefix')."_pncommerce_templates WHERE TemplateID = ".(int)$TemplateID));
            if ( $result != false ) {
                $Template['ID'] = $TemplateID;
                list( $Template['Type'], $Template['Text'], $Template['Desc'] ) = $result[0];
            } else {
                return false;
            }
        }
        $smarty->assign( 'Template', $Template );
        return $smarty->fetch('pncommerce_admin_templateedit.html');
    } else { // submit is set
        list($delete, $TemplateType, $TemplateDesc, $TemplateFile) = pnVarCleanFromInput ('delete', 'TemplateType', 'TemplateDesc', 'TemplateFile');

        if($delete<>1) {
            $TemplateFile = pnVarPrepForOS($TemplateFile);
            if(file_exists($tfile = "modules/pncommerce/pntemplates/" . $TemplateFile) && is_readable($tfile)) {
            if($TemplateID == -1) {
                // new template
                $insertsql = "INSERT INTO ".pnConfigGetVar('prefix')."_pncommerce_templates
                             (TemplateType,
                              TemplateDesc,
                              TemplateText)
                             VALUES ( ".(int)$TemplateType.",
                                     '".pnVarPrepForStore($TemplateDesc)."',
                                     '".pnVarPrepForStore($TemplateFile)."')";
                $res = pnModAPIFunc( 'pncommerce', 'user', 'insertintoDB',
                                     array( 'sql' => $insertsql,
                                            'table' => 'templates',
                                            'idfield' => 'TemplateID' ));
            } else {
                $updatesql = "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_templates
                             SET TemplateType=".(int)$TemplateType.",
                             TemplateDesc='".pnVarPrepForStore($TemplateDesc)."',
                             TemplateText='".pnVarPrepForStore($TemplateText)."' WHERE TemplateID=".(int)$TemplateID;
                $res = pnModAPIFunc( 'pncommerce', 'user', 'executesqlDB',
                                     array('sql' => $updatesql));
            }
            } else {
                pnSessionSetVar('errormsg', pnVarPrepFordisplay(_PNC_INVALIDTEMPLATEFILE));
                pnRedirect( pncAdminModURL( 'pncommerce', 'admin', 'TemplateEdit', array('TemplateID' => $TemplateID) ) );
                return true;
            }
        } else {
            // delete
            $deletesql = "DELETE FROM ".pnConfigGetVar('prefix')."_pncommerce_templates WHERE TemplateID=".(int)$TemplateID;
            $res = pnModAPIFunc( 'pncommerce', 'user', 'executesqlDB',
                                array('sql' => $deletesql));
        }
        pnRedirect( pncAdminModURL( 'pncommerce', 'admin', 'main' ) );
        return true;
    }
}

/**
 * vatedit
 **/
function pncommerce_admin_vatedit ()
{
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $urls = array();
    $urls[admin_vateditresponse] = pncAdminModURL('pncommerce', 'admin', 'vateditresponse');

    //Collect all available VAT's
    $count=1;
    $vats=Array();
    while($count<10)
    {
        $vats[$count]=pnModAPIFunc('pncommerce','user','getVAT', Array('VATID'=>$count));
        $count++;
    }
    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    $smarty->assign( 'Chapter', '1.11' );
    $smarty->assign( 'urls', $urls );
    $smarty->assign( 'vats', $vats );
    return $smarty->fetch( "pncommerce_admin_vatedit.html" );
}

/*
 * vatditresponse
 *
 */
function pncommerce_admin_vateditresponse ($args)
{
    $count=1;
    $VAT=Array();
    while($count<10)
    {
        $VAT[$count]=pnVarCleanFromInput ('VATID'.$count);
        $count++;
    }
    pncloadapi('admin', __FILE__, __LINE__);

    $authid = pnVarCleanFromInput( 'authid' );
    if( !pnSecConfirmAuthKey( $authid ) )
    {
        return showerrorpage( array( 'text' => ""._PNC_BADAUTHKEY ) );
    }

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    $count=1;
    while($count<10)
    {
        pnModAPIFunc('pncommerce','admin','setVAT', Array('VATID'=>$count, 'VAT'=>$VAT[$count]));
        $count++;
    }
    $loc = pncAdminModURL( 'pncommerce', 'admin', 'main');
    pnRedirect( $loc );
    return true;
}

/*
 * export
 *
 */
function pncommerce_admin_export()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    //Create the menu
    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    return $smarty->fetch( 'pncommerce_admin_exportmenu.html' );
}

/*
 * import
 *
 */
function pncommerce_admin_import()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    //Create the menu
    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    return $smarty->fetch( 'pncommerce_admin_importmenu.html' );
}

/*
 * import_table
 *
 */
function pncommerce_admin_import_table()
{
    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    $table = pnVarCleanFromInput('table');
    $config=unserialize(pnModGetVar('pncommerce', 'importconfigtable'));
    $pntable = pnDBGetTables();
    $tablecolumn = &$pntable["pncommerce_".$table."_column"];
    $configitems=unserialize(pnModGetVar('pncommerce', "importconfig".$table));

    if (is_array($tablecolumn))
    {
        $count = 1;
        foreach ($tablecolumn as $cname)
        {
            $tablecolumn1[$count]['Longname'] = $cname;
            $temp = explode( ".", $cname );
            $tablecolumn1[$count]['Shortname'] = $temp[1];
            $count++;
        }
    }
    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    $smarty->assign( 'ColumnList', $tablecolumn1 );
    $smarty->assign( 'Tablename', $table );
    return $smarty->fetch( 'pncommerce_admin_importtable.html' );
}

/*
 * export_table
 *
 */
function pncommerce_admin_export_table()
{
    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    // see which table we have to export
    $table = pnVarCleanFromInput('table');

    $config=unserialize(pnModGetVar('pncommerce', 'exportconfigtable'));
    $pntable = pnDBGetTables();
//    $table = $pntable["pncommerce_".$tab];
    $tablecolumn = &$pntable["pncommerce_".$table."_column"];

    if (is_array($tablecolumn))
    {
        $count = 1;
        foreach ($tablecolumn as $cname)
        {
            $tablecolumn1[$count]['Longname'] = $cname;
            $temp = explode( ".", $cname );
            $tablecolumn1[$count]['Shortname'] = $temp[1];
            $count++;
        }
    }

    $configitems=unserialize(pnModGetVar('pncommerce', "exportconfig".$table));
    $configas=unserialize(pnModGetVar('pncommerce', "exportconfig".$table."as"));

    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    $smarty->assign( 'ColumnList', $tablecolumn1 );
    $smarty->assign( 'Tablename', $table );
    return $smarty->fetch( 'pncommerce_admin_exporttable.html' );
}

function array2xml($items, $xml, $parent = '')
{
    $arrays = array();

    // first process all elementary types, treat them as xml attributes,
    // not as xml tags.
    foreach($items as $key => $item)
    {
        if (is_array($item))
        {
            // we need to remember arrays and process them at the end
            $arrays[$key] = $item;
        }
        else
        {
            $item = str_replace(
                            array('&',    '<',    '>',     '"'),
                            array('&amp;', '&lt;', '&gt;', '&quot;'),
                            $item);
            if (ereg('^[0-9]', $key))
            {
                // Special case for arrays items indexed with integers:
                // xml attributenames must not start with a digit.
                // Make tags of them.
                $xml .= '>' . "\r\n" . '<' . $parent . '_row id="' . $key . '" value="' . $item . '" /';
            }
            else
            {
                $xml .= $key . '="' . $item .'" ';
            }
        }
    } // foreach(elementary data types...
    $xml .= '>' . "\r\n";

    // all elementary types have been processed, now continue with the
    // arrays:
    foreach($arrays as $key => $item)
    {
        if (ereg('^[0-9]', $key))
        {
            // special case for arrays just indexed with integers:
            // xml tagnames must not start with a digit
            $startTag = '<' . $parent . '_row id="' . $key . '" ';
            $endTag = '</' . $parent . '_row>' . "\r\n";
        }
        else
        {
            // named keys / associative arrays
            $startTag = '<' . $key . ' ';
            $endTag = '</' . $key . '>' . "\r\n";
        }

        $xml .= $startTag;
        // recursively call this function
        array2xml($item, &$xml, $key);
        $xml .= $endTag;
    } // foeach(arrays...
} // function array2xml


if (!pnModAPILoad('pncommerce', 'admin'))
{
    return showerrorpage("unable to load pnadminapi", __FILE__, __LINE__);
}
if (!pnModAPILoad('pncommerce', 'user'))
{
    return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
}

/*
 * export_table_send
 *
 */
function pncommerce_admin_export_table_send()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    /*
    if (!pnSecConfirmAuthKey()) {
    pnSessionSetVar('errormsg', _PNC_BADAUTHKEY);
    pnRedirect(pncAdminModURL('pncommerce', 'admin', 'export'));
    return true;
    }
    */
    $config = unserialize(pnModGetVar('pncommerce', 'exportconfig'));
    $select = pnVarCleanFromInput('select');
    $selectas = pnVarCleanFromInput('selectas');
    $table = pnVarCleanFromInput('table');


    for ($j=0; $j<count($select);$j++)
    {
        if($select[$j]!="")
        {
            $tablecolumn[]=$select[$j];
            $tablecolumnas[]=$selectas[$j];
        }
    }

    if (!(is_array($tablecolumn)))
    {
        pnRedirect(pncAdminModURL('pncommerce', 'admin', 'export'));
    }
    if (isset($tablecolumn))
    {
        pnModSetVar('pncommerce', 'exportconfig'.$table, serialize($tablecolumn));
    }
    if (isset($tablecolumnas))
    {
        pnModSetVar('pncommerce', 'exportconfig'.$table.'as', serialize($tablecolumnas));
    }

    $export=$config["export"];
    $separator=$config["separator"];
    $enclosed=$config["enclosed"];
    $escaped=$config["escaped"];
    $add_character=$config["add_character"];
    $pntable = pnDBGetTables();
    $sql="SELECT ";
    foreach ($tablecolumn as $selectcol)
    {
        $sql.="$selectcol, ";
    }
    $sql=substr($sql,0,(strlen($sql)-2));
    $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                            array( 'sql' => $sql." FROM ".pnConfigGetVar('prefix')."_pncommerce_$table" ) );
    if (is_array($result))
    {
        if ($export == 'xml')
        {
            $ext       = 'xml';
            $mime_type = 'text/xml';
            // first add the xml tag
            $dump_buffer .= '<?xml version="1.0" encoding="iso-8859-1"?>'."\r\n";
            // some comments
            $dump_buffer .= '<!-- pncommerce '.pnModGetVar( 'pncommerce', 'Version').' XML-Dump http://www.pncommerce.de (main site)-->'."\r\n";
            // the data
            $dump_buffer .= '<' . $table . '>' . "\r\n";
            foreach ($result as $line)
            {
                $dump_buffer .= '<' . $table . '_row>'."\r\n";
                for ($k=0; $k<count($tablecolumn);$k++)
                {
                    if ($tablecolumnas[$k]=="")
                    {
                        $col=$tablecolumn[$k];
                    }
                    else
                    {
                        $col=$tablecolumnas[$k];
                    }
                    // fix for incorrect serialized data
                    $line[$k] = str_replace('\\"', '"', $line[$k]);
                    // end of fix
                    if (is_array(unserialize($line[$k])))
                    {
                        if (false)
                        {
                            // write arrays down as CDATA being ignored by xml
                            // processors.
                            $dump_buffer .="<".$col.">";
                            $dump_buffer .= '<![CDATA[' . "\r\n";
                            $dump_buffer .= $line[$k] . "\r\n";
                            $dump_buffer .= ']]>' . "\r\n";
                        }
                        else
                        {
                            // Array: just open tag, array items will be
                            // added as attributes
                            $dump_buffer .="<".$col . " ";
                            array2xml(unserialize($line[$k]), &$dump_buffer);
                        }
                    }
                    else
                    {
                        // elementary data type
                        $dump_buffer .="<".$col.">";
                        $line[$k] = str_replace(
                                        array('<',    '>',    '&'    , '"'),
                                        array('&lt;', '&gt;', '&amp;', '&quot;'),
                                        $line[$k]);
                        $dump_buffer .= $line[$k];
                    }
                    $dump_buffer .="</".$col.">\r\n";
                }
                $dump_buffer .= "</" . $table ."_row>\r\n";
            }
            $dump_buffer .= '</' . $table . '>' . "\r\n";
        }
        else
        {
            $ext       = 'csv';
            $mime_type = 'text/x-csv';
            if ($export == 'excel')
            {
                $separator = ',';
                $enclosed = '"';
                $escaped = '';
            }
            // the data
            foreach ($result as $line){$i=0;
            foreach ($tablecolumn as $col)
            {
                $dump_buffer .="$enclosed";
                $dump_buffer .= addslashes($line[$i])."";
                $dump_buffer .="$enclosed"."$separator";
                $i++;
            }
            if ($add_character=="\\n"){
              $dump_buffer .= "\n";}
            elseif ($add_character=="\\r\\n"){
              $dump_buffer .= "\r\n";}
            elseif ($add_character=="\\n\\r"){
              $dump_buffer .= "\n\r";}
            elseif ($add_character=="\\r"){
              $dump_buffer .= "\r";}
            else{
              $dump_buffer .= "\n";}
            }
            $dump_buffer=trim($dump_buffer);
        }
        //send the headers and the file
        header('Content-Type: ' . $mime_type);
        header('Expires: ' . $now);
        $filename=$table;
        preg_match( "/MSIE/i",  $_SERVER["HTTP_USER_AGENT"], $match);
        if ( $match[0] == 'MSIE')
        {
            header('Content-Disposition: inline; filename="' . $filename . '.' . $ext . '"');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
        }
        else
        {
            header('Content-Disposition: attachment; filename="' . $filename . '.' . $ext . '"');
            header('Pragma: no-cache');
        }
        echo $dump_buffer;
        exit;
    }//endif issaray($result)
    else
    {
        pnSessionSetVar('errormsg', _PNC_NOENTRYFOUND);
        pnRedirect(pncAdminModURL('pncommerce', 'admin', 'export'));
        return true;
    }
}

/*
 * import_table_get
 *
 */
function pncommerce_admin_import_table_get()
{
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
/*
    if (!pnSecConfirmAuthKey()) {
        pnSessionSetVar('errormsg', _PNC_BADAUTHKEY);
        pnRedirect(pncAdminModURL('pncommerce', 'admin', 'export'));
        return true;
    }
*/
    $config=unserialize(pnModGetVar('pncommerce', 'exportconfig'));
    list( $table, $select, $textfile, $replace ) = pnVarCleanFromInput( 'table', 'select', 'textfile', 'replace' );

    if (is_array($textfile))
    {
        $textfile=$textfile[tmp_name];
    }
    if ($textfile=="")
    {
        pnSessionSetVar('errormsg', _PNC_FILEFAILED);
        pnRedirect( pnModURL( 'pncommerce', 'admin', 'import' ) );
        return true;
    }
    for ($j=0; $j<count($select);$j++)
    {
        if($select[$j]!="")
        {
            $tablecolumn[]=$select[$j];
        }
    }
    pnModSetVar('pncommerce', 'importconfig$table', serialize($tablecolumn));

/*
    if($table==pnConfigGetVar('prefix')."_".'pncommerce'."_items")
    {
        pnModSetVar('pncommerce', 'importconfigitems', serialize($tablecolumn));
    }
    elseif($table==pnConfigGetVar('prefix')."_".'pncommerce'."_users")
    {
        pnModSetVar('pncommerce', 'importconfigusers', serialize($tablecolumn));
    }
    elseif($table==pnConfigGetVar('prefix')."_".'pncommerce'."_category")
    {
        pnModSetVar('pncommerce', 'importconfigcategory', serialize($tablecolumn));
    }
*/
    chmod($textfile, 0777);
    $export=$config["export"];
    $separator=addslashes($config["separator"]);
    $enclosed=$config["enclosed"];
    $escaped=addslashes($config["escaped"]);
    $lineterminator=$config["add_character"];
    //build the statment
    $sql="LOAD DATA INFILE '".$textfile."'";
    if (!empty($replace))
    {
        $sql .= " " . $replace;
    }
    $sql .= " INTO TABLE ".$table;
    if (isset($separator))
    {
        $sql .= " FIELDS TERMINATED BY '" . $separator . "'";
    }
    if (strlen($enclosed) > 0)
    {
        $sql .= " ENCLOSED BY '" . $enclosed . "'";
    }
    if (strlen($escaped) > 0)
    {
        $sql .= " ESCAPED BY '" . $escaped . "'";
    }
    if (strlen($lineterminator) > 0)
    {
        $sql .= " LINES TERMINATED BY '" . $lineterminator . "'";
    }
    if (is_array($tablecolumn))
    {
        $sql .=" (";
        foreach ($tablecolumn as $a)
        {
            $sql .= $a.", ";
        }
        $sql = substr( $sql, 0 , (strlen( $sql ) - 2 ) );
        $sql .= ")";
    }
    if( pnModAPIFunc( 'pncommerce', 'user', 'executesqlDB',
                      array( 'sql' => $sql ) ) == true )
    {
        pnSessionSetVar( 'statusmsg', _PNC_IMPORTSUCCESS );
    }
    else
    {
        pnSessionSetVar( 'errormsg', _PNC_IMPORTFAILED );
    }
    pnRedirect( pnModURL( 'pncommerce', 'admin', 'import' ) );
    return true;
}

/*
 * export_config
 *
 */
function pncommerce_admin_export_config()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    //Get all available Config
    $import = pnVarCleanFromInput('import');
    $config=unserialize(pnModGetVar('pncommerce', 'exportconfig'));

    //build the real configuration array
    $realconfig = array();
    if( $import == true )
    {
        $realconfig['Title'] = ""._PNC_CONFIGIMPORT;
    }
    else
    {
        $realconfig['Title'] = ""._PNC_CONFIGEXPORT;
    }
    $realconfig['Import'] = $import;
    $realconfig['Separator']    = htmlspecialchars($config["separator"]);
    $realconfig['Enclosed']     = htmlspecialchars($config["enclosed"]);
    $realconfig['Escaped']      = htmlspecialchars($config["escaped"]);
    $realconfig['AddCharacter'] = htmlspecialchars($config["add_character"]);
    $realconfig['Export'] = $config["export"];
    $realconfig['Excel'] = "";
    $realconfig['CSV']   = "";
    $realconfig['XML']   = "";

    $export = $config["export"];
    switch( $export )
    {

        case 'excel' :
                $realconfig['ExcelHTML'] = "checked";
                break;
        case "csv" :
                $realconfig['CSVHTML'] = "checked";
                break;
        case "xml" :
                $realconfig['XMLHTML'] = "checked";
                break;
    }

    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    $smarty->assign( 'Config', $realconfig );
    return $smarty->fetch( 'pncommerce_admin_importexportconfig.html' );

}

/*
 *export_update_config
 *
 */
function pncommerce_admin_export_update_config()
{
    if (!pnSecAuthAction(0, 'pncommerce::config', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $import = pnVarCleanFromInput('import');
    $export = pnVarCleanFromInput('export');
    $separator = pnVarCleanFromInput('separator');
    $enclosed = pnVarCleanFromInput('enclosed');
    $escaped = pnVarCleanFromInput('escaped');
    $add_character =pnVarCleanFromInput('add_character');

    $config = array( "export" => $export,
                     "separator" => $separator,
                     "enclosed" => $enclosed,
                     "escaped" => $escaped,
                     "add_character" => $add_character);
    if (isset($export))
    {
        pnModSetVar('pncommerce', 'exportconfig', serialize($config));
    }
    pnSessionSetVar('statusmsg', pnVarPrepForDisplay(_PNC_UPDATEDCONFIG) );

    if ($import==true)
    {
        pnRedirect(pncAdminModURL('pncommerce', 'admin', 'import'));
        return true;
    }
    else
    {
        pnRedirect(pncAdminModURL('pncommerce', 'admin', 'export'));
        return true;
    }
}

/*
 * itemsearch
 *
 */
function pncommerce_admin_itemsearch()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::item', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }


    $search = pnVarCleanFromInput( 'search' );

    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;

    if( !$search )
    {
        $sql = pnSessionGetVar( 'PNCAdminItemSearchQuery' );
    }
    else
    {
        list($searchstring, $searcharea, $orderby) = pnVarCleanFromInput( 'SearchString', 'SearchArea', 'OrderBy' );
        $sql = "SELECT ItemID FROM ".pnConfigGetVar('prefix')."_pncommerce_items WHERE";
        if ( $searcharea == "0" )
        {
            $sql.=" ItemSKU LIKE '%".pnVarPrepForStore($searchstring)."%'
                 OR ItemDescription LIKE '%".pnVarPrepForStore($searchstring)."%'
                 OR ItemName LIKE '%".pnVarPrepForStore($searchstring)."%'
                 ORDER BY ".pnVarPrepForStore($orderby).";";
        }
        elseif ($searcharea != "")
        {
            $sql.=" $searcharea LIKE '%".pnVarPrepForStore($searchstring)."%'
                    ORDER BY ".pnVarPrepForStore($orderby).";";
        }
        pnSessionSetVar( 'PNCAdminItemSearchQuery', $sql );
    }
    $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                            array( 'sql' => $sql ) );
    if( $result <> false )
    {
        $ItemArray = array();
        foreach( $result as $resultline )
        {
            // read the Item and put it into an array
            array_push( $ItemArray, pnModAPIFunc( 'pncommerce', 'user', 'getItem', array( 'ItemID' => $resultline[0] ) ) );
        }
    }
    $smarty->assign( 'ItemList', $ItemArray );
    $smarty->assign( 'ItemCount', count( $ItemArray ) );
    $smarty->assign( 'SearchAreaList', array( '0' => _PNC_SEARCHCOMPLETE, 'ItemSKU' => _PNC_PRODUCTNUMBER, 'ItemName' => _PNC_PRODUCTNAME, 'ItemDescription' => _PNC_DESCRIPTION ) );
    $smarty->assign( 'SearchArea', $SearchArea );
    $smarty->assign( 'OrderByList', array( 'ItemID' => _PNC_PRODUCTID, 'ItemSKU' => _PNC_PRODUCTNUMBER, 'ItemName'=> _PNC_PRODUCTNAME ) );
    $smarty->assign( 'OrderBy', $orderby );
    $smarty->assign( 'SearchString', $searchstring );

    return $smarty->fetch( 'pncommerce_admin_itemsearch.html' );
}

/*
 * structuretree
 * Shows a structured tree of categories and items
 *
 *@params$args['mode'] int either 1 = expand or 2 = collapse all categories
 *
 */
function pncommerce_admin_structuretree()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0,
                   'pncommerce::category',
                   '::',
                   ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $mode = (int)pnVarCleanFromInput('mode');

	$temp = pnSessionGetVar("Open");
	if( @unserialize($temp) <> "" )
	{
	    $Open = unserialize( $temp );
	}
	else
	{
	    $Open = array();
	}

    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    $smarty->assign('showCat',pnVarCleanFromInput('showCat'));
    $smarty->assign('open', $Open);
    return $smarty->fetch( "pncommerce_admin_structuretree.html" ,time());
}

/*
 * resendemail
 *
 */
function pncommerce_admin_resendemail ($args)
{
    list( $ON, $KID, $MailType ) = pnVarCleanFromInput ( 'ON', 'KID', 'MailType' );
    pncloadapi('user', __FILE__, __LINE__);

    if( $MailType == 1 )
    {
        $success = pnModAPIFunc( 'pncommerce', 'user', 'sendEmail',
                                 array( 'KID' => $KID,
                                        'ON'  => $ON,
                                        'customer' => true ) );
        $type = pnVarPrepForDisplay( _PNC_CUSTOMEREMAIL );
    }
    else
    {
        $success = pnModAPIFunc( 'pncommerce', 'user', 'sendEmail',
                                 array( 'KID' => $KID,
                                        'ON'  => $ON,
                                        'customer' => false ) );
        $type = pnVarPrepForDisplay( _PNC_INTERNALEMAIL );
    }
    if( $success == true )
    {
            pnSessionSetVar( "statusmsg", "".pnVarPrepForDisplay( _PNC_MAILSUCCESSFULSENT )." ($type)" );
    }
    else
    {
            pnSessionSetVar( "statusmsg", "".pnVarPrepForDisplay( _PNC_ERRORSENDINGMAIL )." ($type)" );
    }
    pnRedirect ( pncAdminModURL( 'pncommerce', 'user', 'receipt', array('ON' => $ON, 'User' => $KID, 'Admin'=>true) ) );
    return true;
}

/**
 * reports
 *
 **/
function pncommerce_admin_reports()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0,
                    'pncommerce::category',
                    '::',
                    ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    $function= pnVarCleanFromInput ( 'function' );
    if ($function==""){$function="statistics";}


    if ($function=="statistics")
    {
        return pncommerce_admin_statistics();
    }else
    {
        return pncommerce_admin_orderstatistics();
    }
}

/*
 * statistics
 *
 */
function pncommerce_admin_statistics()
{
    pncloadapi('useradmin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0,
                    'pncommerce::',
                    '::',
                    ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    $Reports=pnModAPIFunc('pncommerce','admin','calculateBasicStats','');
    $smarty->assign('Reports',$Reports);
//    echo "<pre>";print_r($Reports);echo "</pre>";
    return $smarty->fetch( "pncommerce_admin_statistics.html" );
}

/*
 * internal function Ascii_Sort
 * Thanks to www.about.com for the basic function
 */
function Ascii_Sort($val_1, $val_2)
{
    if($val_1 > $val_2)
    {
        return 1;
    }
    else if($val_1 < $val_2)
    {
        return -1;
    }
    return 0;
}

/*
 * debuginfo
 *
 *@params 'checkmd5' int if 1 then start md5 check
 *@returns pnRender output
 */
function pncommerce_admin_debuginfo()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $checkmd5 = (int)pnVarCleanFromInput('checkmd5');
    $usemd5server = (int)pnVarCleanFromInput('usemd5server');

    $checkmd5 = ($checkmd5==1) ? true : false;
    $curl = true;//($checkmd5==true) &&
    if(  (function_exists('curl_init')==false) )
    {
        $checkmd5 = false;
        $curl = false;
        $allmd5servers = false;
    }
    else
    {
        //
        if( pnSessionGetVar('PNCMD5Servers') == false )
        {
            $allmd5servers = array(  array( "name"   => "pncommerce.de",
                                            "url"    => "update.pncommerce.de",
                                            "status" => false ),
                                     array( "name"   => "pncommerce.com",
                                            "url"    => "support.pncommerce.com",
                                            "status" => false ) );
            for( $x=0; $x<count($allmd5servers); $x++ )
            {

                // check if server is available and get the status information
                $cu = curl_init("http://" . $allmd5servers[$x]['url'] ."/md5check.php?cmd=status");
                curl_setopt( $cu, CURLOPT_USERAGENT, "pncommerce" );
                curl_setopt( $cu, CURLOPT_RETURNTRANSFER, 1 );
                $resp = curl_exec($cu);
                curl_close($cu);
                // quick and dirty: check if the response is longer than 35 chars
                // if yes, we probably encounter a 404
                if((strlen($resp)<35) && (strlen($resp)>5))
                {
                    $allmd5servers[$x]["status"] = $resp;
                }
            }
            pnSessionSetVar('PNCMD5Servers', serialize($allmd5servers) );
        }
        else
        {
            $allmd5servers = unserialize(pnSessionGetVar('PNCMD5Servers'));
        }
    }
    // format of localfiles array:
    // $localfiles[name] = array( 'md5' => "", 'revision' => "", 'author' => "", 'date' => "");
    $localfiles=array();
    $localfiles = dirscan( "modules/pncommerce/" );
    if($checkmd5==true)
    {
        $cu = curl_init("http://" . $allmd5servers[$usemd5server]['url'] . "/md5check.php?cmd=getlist");
        curl_setopt( $cu, CURLOPT_USERAGENT, "pncommerce" );
        curl_setopt( $cu, CURLOPT_RETURNTRANSFER, 1 );
        $body = curl_exec($cu);
        curl_close($cu);

        $lines = explode( "<br />", $body);
        // 0 = count
        unset($lines[0]);
        //echo "result:$body:<br />";
        $serverfiles = array();
        // format of serverfile array:
        // 0 = filename
        // 1 = servermd5
        // 2 = serverrevision

        $onlylocal = array();
        $onlyserver = array();
        $serverandlocal = array();
        foreach($lines as $line)
        {
            // break out the data from the string
            list( $sname, $smd5, $srev, $sauthor, $sdate ) = explode(":", $line);
            // compare local files and server files
            // if the file exists locally and on the server we compare
            // if local only -> special array $onlylocal
            // if server only -> special array $onlyserver
            if(array_key_exists( $sname, $localfiles))
            {
                // server file exists locally
                $serverandlocalfiledata = array();
                $serverandlocalfiledata['md5match'] = ($smd5 == $localfiles[$sname]['localmd5']) ? true : false;
                $serverandlocalfiledata['revisionmatch'] = ($srev == $localfiles[$sname]['localrevision']) ? true : false;
                $serverandlocalfiledata['serverrevision'] = $srev;
                $serverandlocalfiledata['localrevision']  = $localfiles[$sname]['localrevision'];
                $serverandlocalfiledata['servermd5'] = $smd5;
                $serverandlocalfiledata['localmd5'] = $localfiles[$sname]['localmd5'];
                $serverandlocalfiledata['localauthor'] = $localfiles[$sname]['author'];
                $serverandlocalfiledata['localdate']   = $localfiles[$sname]['date'];
                $serverandlocalfiledata['serverauthor'] = $sauthor;
                $serverandlocalfiledata['serverdate']   = $sdate;
                $serverandlocal[$sname] = $serverandlocalfiledata;
                // we remove the entry from the localfiles array
                $localfiles[$sname] = false;
            }
            else
            {
                // server file does not exist locally
                $onlyserverfiledata = array();
                $onlyserverfiledata['md5match'] = false;
                $onlyserverfiledata['revisionmatch'] = false;
                $onlyserverfiledata['serverrevision'] = $srev;
                $onlyserverfiledata['localrevision']  = "";
                $onlyserverfiledata['servermd5'] = $smd5;
                $onlyserverfiledata['localmd5'] = "";
                $onlyserverfiledata['localauthor'] = "";
                $onlyserverfiledata['localdate']   = "";
                $onlyserverfiledata['serverauthor'] = $sauthor;
                $onlyserverfiledata['serverdate']   = $sdate;
                $onlyserver[$sname] = $onlyserverfiledata;
            }
            unset($sname);
            unset($smd5);
            unset($srev);
        }
        //
        foreach($localfiles as $lfilename=>$lfiledata)
        {
            if($lfiledata <> false)
            {
                $onlylocal[$lfilename] = $lfiledata;
            }
        }
    }
    else
    {
        $onlylocal = false;
        $onlyserver = false;
        $serverandlocal = $localfiles;
    }

    $pnr =& new pnRender('pncommerce');
    $pnr->caching = false;
    $pnr->assign( 'serverandlocal', $serverandlocal );
    $pnr->assign( 'onlylocal', $onlylocal );
    $pnr->assign( 'onlyserver', $onlyserver );
    $pnr->assign( 'curl', $curl );
    $pnr->assign( 'checkmd5', $checkmd5 );
    $pnr->assign( 'md5servers', $allmd5servers);
    return $pnr->fetch( "pncommerce_admin_debuginfo.html" );
}

function dirscan($dirname)
{
//    echo "<br />entering '$dirname'<br />";
    $found = array();
    $dir = opendir($dirname);
    while ( $file = readdir( $dir ) )
    {
        if( $file != "." &&
            $file != ".." &&
            $file != "index.html" &&
            $file != "pnimages" &&
            $file != "category_images" &&
            $file != "product_images" &&
            $file != "CVS"
            )
        {
            $file = $dirname . $file;
//            echo "--".$file."--";
            if(is_dir($file))
            {
//                echo "***";
                $newfound = array();
                $newfound = dirscan($file . "/" );
                uksort( $newfound, "Ascii_Sort" );
                $found = array_merge($found, $newfound);
            }
            else
            {
                $data = getmd5andrevision($file);
                $found[str_replace( "modules/pncommerce/", "", $file)] = array( 'localmd5' => $data[0], 'localrevision' => $data[1], 'author' => $data[2], 'date' => $data[3]);
            }
//            echo "<br />";
        }
    }
    return $found;
}

function getmd5andrevision($filename)
{
    if(file_exists($filename))
    {
        $line = file($filename);
        $md5 = md5(implode("", $line));
        for( $x=0;$x<=20;$x++ )
        {
            // check for author
            if ( strstr( $line[$x], '$Author:' ) )
            {
                $t1 = substr_replace( $line[$x], "", 0, strpos( $line[$x], "$" )+1 );
                $t1 = substr_replace( $t1, "", strrpos( $t1, "$" ), strlen( $t1 ) );
                $t2 = explode( ":", $t1);
                $author = trim($t2[1]);
                continue;
            }
            // check for revision
            if ( strstr( $line[$x], '$Revision:' ) )
            {
                $t1 = substr_replace( $line[$x], "", 0, strpos( $line[$x], "$" )+1 );
                $t1 = substr_replace( $t1, "", strrpos( $t1, "$" ), strlen( $t1 ) );
                $t2 = explode( ":", $t1);
                $revision = trim($t2[1]);
                continue;
            }
            // check for date
            if ( strstr( $line[$x], '$Date:' ) )
            {
                $t1 = substr_replace( $line[$x], "", 0, strpos( $line[$x], "$" )+1 );
                $t1 = substr_replace( $t1, "", strrpos( $t1, "$" ), strlen( $t1 ) );
                $t2 = explode( " ", $t1);
                $date = trim($t2[1]);
                continue;
            }
        }
        return array( $md5, $revision, $author, $date);
    }
    return array( "", "", "", "");
}

/*
 * phpinfo
 *
 */
function pncommerce_admin_phpinfo()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0,
                    'pncommerce::',
                    '::',
                    ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    // the following lines of code are taken from the bcphpinfo module
    // http://www.bravecobra.com
    ob_start();
    phpinfo(INFO_ALL);
    $info = ob_get_contents();
    ob_end_clean();
	$position = strpos($info,"<body>");
	$info = substr($info, $position+6);
    //and everytag after </body>
	$info = str_replace("</body>","",$info);
	$info = str_replace("</html>","",$info);

    $smarty =& new pnRender('pncommerce');
    $smarty->caching = false;
    $smarty->assign( 'phpinfo', $info );
    return $smarty->fetch( "pncommerce_admin_phpinfo.html" );
}

/*
 * validatedatabase
 *
 */
function pncommerce_admin_validatedatabase()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0,
                    'pncommerce::',
                    '::',
                    ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $submit = pnVarCleanFromInput( 'Submit' );

    if( !$submit )
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        return $smarty->fetch( 'pncommerce_admin_validatedatabase.html' );
    }
    else
    {
        // we need to set the shop inactive to avoid collisions when rebuilding database tables
        pnModSetVar( 'pncommerce', 'status', 'off' );
        // read the admins choice
        if( pnVarCleanFromInput( 'option1' ) == 'on' )
        {
            // rebuild OrderedQuantity
            $res = pnModAPIFunc( 'pncommerce', 'admin', 'rebuildOrderedQuantity' );
        }
        // make the shop active again
        pnModSetVar( 'pncommerce', 'status', 'on' );
    }
    pnRedirect(pncAdminModURL('pncommerce', 'admin', 'main'));
    return true;
}

/*
 * changeActiveState
 *
 */
function pncommerce_admin_changeActiveState()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0,
                    'pncommerce::',
                    '::',
                    ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    $state = pnModGetVar( 'pncommerce', 'status' );
    if( $state == 'off' )
    {
        // activate shop
        pnModSetVar( 'pncommerce', 'status', 'on' );
    }
    else
    {
        // deactivate shop
        pnModSetVar( 'pncommerce', 'status', 'off' );
    }
    pnRedirect(pncAdminModURL('pncommerce', 'admin', 'main'));
    return true;
}

/**
 * ModificationConfig
 *
 */
function pncommerce_admin_ModificationConfig()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $Submit = pnVarCleanFromInput( 'Submit' );
    if( !$Submit )
    {
        // first we read the pnfm* files according to the sequence settings in the modvar
        // *ModifierSequence, then we read the remaining pnfm*'s

        // per order
        list( $names1, $activeorderfms ) = pnModAPIFunc( 'pncommerce', 'admin', 'readactiveModifierInfo', array( 'type' => 'order' ) );
        // per item
        list( $names2, $activeitemfms ) = pnModAPIFunc( 'pncommerce', 'admin', 'readactiveModifierInfo', array( 'type' => 'item' ) );
        // per preorder
        list( $names3, $activepreorderfms ) = pnModAPIFunc( 'pncommerce', 'admin', 'readactiveModifierInfo', array( 'type' => 'preorder' ) );
        // per postorder
        list( $names4, $activepostorderfms ) = pnModAPIFunc( 'pncommerce', 'admin', 'readactiveModifierInfo', array( 'type' => 'postorder' ) );

        // join all the arrays containing the names together in one array
        $activefmname = array_merge( $names1, $names2, $names3, $names4 );

        // now scan for the remaining pnfm*'s
        $dir = opendir ( "modules/pncommerce" );
        $count = 1;
        $inactivefms = array();
        while ( $fm = readdir( $dir ) )
        {
            if ( ereg("pnfm", $fm) )
            {
                // modifier found
                // remove api.php
                $fm1 = str_replace("api.php", "", $fm);
                // remove leading pn
                $fm1 = substr( $fm1, 2, strlen($fm1) - 2 );
//              if( ( !in_array( $fm1, $ordermodsequence ) ) && ( !in_array( $fm1, $itemmodsequence ) ) && ( !in_array( $fm1, $premodsequence ) ) && ( !in_array( $fm1, $postmodsequence ) ) )
                if( !array_key_exists( $fm1, $activefmname ) )
                {
                    pncloadapi($fm1, __FILE__, __LINE__);
                    $mode = pnModGetVar ('pncommerce', $fm1);

                    $inactivefms[$count]=array(
                         'name'=> $fm1,
                         'info'=> pnModAPIFunc ('pncommerce', $fm1, 'info' ),
                         'type'=> pnModAPIFunc ('pncommerce', $fm1, 'type' ),
                         'mode'=> $mode );
                    if ( $mode == 'on' )
                    {
                        $inactivefms[$count]['state']=""._PNC_ACTIVE;
                    }
                    else if ( $mode == 'off' )
                    {
                        $inactivefms[$count]['state']=""._PNC_INACTIVE;
                    }
                    else
                    {
                        $inactivefms[$count]['state']=""._PNC_NOTINSTALLED   ;
                    }
                    $count++;
                }
            }
        }
        $smarty =& new pnRender( 'pncommerce' );
        $smarty->caching = false;
        $smarty->assign( 'activeordermodifiers', $activeorderfms );
        $smarty->assign( 'activeordermodcount', count( $activeorderfms ) );
        $smarty->assign( 'activeitemmodifiers', $activeitemfms );
        $smarty->assign( 'activeitemmodcount', count( $activeitemfms ) );
        $smarty->assign( 'activepreordermodifiers', $activepreorderfms );
        $smarty->assign( 'activepreordermodcount', count( $activepreorderfms ) );
        $smarty->assign( 'activepostordermodifiers', $activepostorderfms );
        $smarty->assign( 'activepostordermodcount', count( $activepostorderfms ) );
        $smarty->assign( 'inactivemodifiers', $inactivefms );
        $smarty->assign( 'inactivecount', count( $inactivefms ) );
        return $smarty->fetch( 'pncommerce_admin_modificationconfig.html' );
    }
    else   // submit is set
    {
        return true;
    }
}

/**
 * changemodsequence
 *
 *@params ['mod'] string modifier name
 *@params ['mtype'] string 'item' or 'order'
 */
function pncommerce_admin_changemodsequence()
{
    pncloadapi('admin', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN))
    {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    list( $dir, $mod, $mtype ) = pnVarCleanFromInput( 'dir', 'mod', 'mtype' );

    $modtypearray= array( 'item' => 'ItemModifierSequence',
                          'order' => 'OrderModifierSequence',
                          'preorder' => 'PreOrderModifierSequence',
                          'postorder' => 'PostOrderModifierSequence' );
    if( !isset( $modtypearray[$mtype] ) )
    {
        return false;
    }
    $modsequence = unserialize( pnModGetVar( 'pncommerce', $modtypearray[$mtype] ) );
    $newsequence = array();
    if( $dir == "down" )
    {
        for($j=0;$j<count($modsequence);$j++)
        {
            $temp = current($modsequence);
            if( $temp == $mod )
            {
                next($modsequence);
                array_push( $newsequence, current($modsequence) );
                array_push( $newsequence, $temp );
            }
            else
            {
                array_push( $newsequence, current($modsequence) );
            }
            next($modsequence);
        }
        array_pop($newsequence);
    }
    elseif( $dir == "up" )
    {
        end($modsequence);
        for($j=0;$j<count($modsequence);$j++)
        {
            $temp = current($modsequence);
            if( $temp == $mod )
            {
                prev($modsequence);
                array_push( $newsequence, current($modsequence) );
                array_push( $newsequence, $temp );
            }
            else
            {
                array_push( $newsequence, current($modsequence) );
            }
            prev($modsequence);
        }
        array_pop($newsequence);
        $newsequence = array_reverse($newsequence);
    }
    pnModSetVar( 'pncommerce', $modtypearray[$mtype], serialize( $newsequence ) );
    pnRedirect( pncAdminModURL('pncommerce', 'admin', 'modificationconfig' ) );
    return true;
}

/**
 * searchcustomer
 *
 */
function pncommerce_admin_customersearch()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0,
                    'pncommerce::',
                    '::',
                    ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    $search = pnVarCleanFromInput( 'search' );
    $smarty =& new pnRender( 'pncommerce' );
    $smarty->caching = false;
    $orderbylist = array( 'UserName'         => _PNC_USERNAME,
                          'Name'             => _PNC_INVOICEADDRESS." ("._PNC_NAME.")",
                          'Address1'         => _PNC_INVOICEADDRESS." ("._PNC_ADDRESS1.")",
                          'Address2'         => _PNC_INVOICEADDRESS." ("._PNC_ADDRESS1.")",
                          'City'             => _PNC_INVOICEADDRESS." ("._PNC_CITY.")",
                          'State'            => _PNC_INVOICEADDRESS." ("._PNC_STATE.")",
                          'Zip'              => _PNC_INVOICEADDRESS." ("._PNC_ZIP.")",
                          'Country'          => _PNC_INVOICEADDRESS." ("._PNC_COUNTRY.")",
                          'Email'            => _PNC_EMAIL,
                          'DayPhone'         => _PNC_DAYTIMEPHONE,
                          'EvePhone'         => _PNC_EVENINGPHONE,
                          'PayMethod'        => _PNC_PAYMETHOD,
                          'ShippingMethod'   => _PNC_SHIPPINGMETHOD,
                          'ShipToName'       => _PNC_SHIPPINGADDRESS." ("._PNC_NAME.")",
                          'ShipToAddress1'   => _PNC_SHIPPINGADDRESS." ("._PNC_ADDRESS1.")",
                          'ShipToAddress2'   => _PNC_SHIPPINGADDRESS." ("._PNC_ADDRESS2.")",
                          'ShipToCity'       => _PNC_SHIPPINGADDRESS." ("._PNC_CITY.")",
                          'ShipToState'      => _PNC_SHIPPINGADDRESS." ("._PNC_STATE.")",
                          'ShipToZip'		 => _PNC_SHIPPINGADDRESS." ("._PNC_ZIP.")",
                          'ShipToCountry'	 => _PNC_SHIPPINGADDRESS." ("._PNC_COUNTRY.")" );
    $fieldnamesarray = array_keys( $orderbylist );
    $searcharealist = array_merge( array("0" => _PNC_COMPLETE ), $orderbylist );


    if( !$search )
    {
        $sql = pnSessionGetVar( 'PNCAdminCustomerSearchQuery' );
    }
    else // if( isset($searchstring) )
    {
        list($searchstring, $searcharea, $orderby) = pnVarCleanFromInput( 'SearchString', 'SearchArea', 'OrderBy' );
        $sql = "SELECT UserName FROM ".pnConfigGetVar('prefix')."_pncommerce_users WHERE";
        if ( $searcharea == "0" )
        {
            foreach( $fieldnamesarray as $fieldname )
            {
            //OR in this string  is used as "or" during the loop and as start for "or"der when it's done

                $sql.=" $fieldname LIKE '%".pnVarPrepForStore($searchstring)."%' OR";
            }
            $sql .= "DER BY ".pnVarPrepForStore($orderby).";";
        }
        elseif ($searcharea != "")
        {
            $sql.=" $searcharea LIKE '%".pnVarPrepForStore($searchstring)."%'
                    ORDER BY ".pnVarPrepForStore($orderby).";";
        }
        // for later use we store the query in a session variable
        pnSessionSetVar( 'PNCAdminCustomerSearchQuery', $sql );
    }
    $result = pnModAPIFunc( 'pncommerce', 'user', 'readfromDBpreformat',
                            array( 'sql' => $sql ) );
    if( $result <> false )
    {
        $CustomerArray = array();
        foreach( $result as $resultline )
        {
            // read the Item and put it into an array
            array_push( $CustomerArray, pnModAPIFunc( 'pncommerce', 'user', 'getUserdata', array( 'KID' => $resultline[0] ) ) );
        }
        $smarty->assign( 'CustomerList', $CustomerArray );
        $smarty->assign( 'CustomerCount', count( $CustomerArray ) );
    }
    $smarty->assign( 'SearchAreaList', $searcharealist );
    $smarty->assign( 'SearchArea', $searcharea );
    $smarty->assign( 'OrderByList', $orderbylist );
    $smarty->assign( 'OrderBy', $orderby );
    $smarty->assign( 'SearchString', $searchstring );
    return $smarty->fetch( 'pncommerce_admin_customersearch.html' );
}

/**
 * editscheme
 *
 */
function pncommerce_admin_editscheme()
{
    pncloadapi('admin', __FILE__, __LINE__);
    pncloadapi('user', __FILE__, __LINE__);

    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    list($scheme_id, $submit) = pnVarCleanFromInput('schemeid', 'submit');

    if(!isset($scheme_id) || !is_numeric($scheme_id)) {
        return showerrorpage(_MODARGSERROR, __FILE__, __LINE__);
    }

    $scheme = pnModAPIFunc('pncommerce', 'admin', 'schemeGet',
                            array('scheme_id' => $scheme_id));
    if(!$submit) {
        $pnr =& new pnRender('pncommerce');
        $pnr->caching = false;
        $pnr->assign('scheme', $scheme);
        $pnr->assign('availableproperties', pnModAPIFunc('pncommerce', 'admin', 'getAvailablePlugins', array('type' => 'pr')));
        return $pnr->fetch('pncommerce_admin_editscheme.html');
    } else { // submit is set
        list($scheme['deletescheme'],
             $scheme['template_id'],
             $scheme['name'],
             $scheme['description']) = pnVarCleanFromInput('deletescheme', 'templateid', 'schemename', 'description');
/*
        if(empty($scheme['template_id']) || empty($scheme['name']) ) {
            return showerrorpage(_MODARGSERROR, __FILE__, __LINE__);
        }
*/
        if($deletescheme==1) {
            pnModAPIFunc('pncommerce', 'admin', 'schemeDelete',
                         array('scheme_id' => $scheme_id));
            pnRedirect(pnModURL('pncommerce','admin', 'main'));
        } else {
            $scheme_id = pnModAPIFunc('pncommerce', 'admin', 'schemeSet',
                            array('scheme' => $scheme));
            // let the properties api do the update themself
            foreach($scheme['properties'] as $oldproperty) {
                pncloadapi($oldproperty['type'], __FILE__, __LINE__);
                pnModAPIFunc('pncommerce', $oldproperty['type'], 'processSchemeForm',
                             array('oldproperty' => $oldproperty));
            }

            if($scheme_id==false) {
                return showerrorpage(_PNC_ERRORWRITINGSCHEME, __FILE__, __LINE__);
            }
            pnRedirect(pnModURL('pncommerce', 'admin', 'editscheme', array('schemeid' => $scheme_id)));
        }
        return true;
    }
}

/**
 * addproperty
 *
 *@params $args['']
 *@returns nothing, forwards to editscheme
 */
function pncommerce_admin_addproperty()
{
    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }

    pncloadapi('admin', __FILE__, __LINE__);

    list($addproperty, $scheme_id) = pnVarCleanFromInput('addproperty', 'schemeid');
    if(isset($addproperty)) {
        // do it
        list($newtype, $newsortorder)  = pnVarCleanFromInput('newpropertytype', 'newpropertysortorder');
//pncdebug('so', $newsortorder, true);
        pncloadapi($newtype, __FILE__, __LINE__);
        $scheme = pnModAPIFunc('pncommerce', 'admin', 'schemeGet', array('scheme_id' => $scheme_id));
        $newproperty = pnModAPIFunc('pncommerce', $newtype, 'new', array('sortorder' => $newsortorder));
        $newproperty['scheme_id'] = $scheme_id;
        $newproperty['scheme_type'] = $scheme['type'];
        $newproperty = pnModAPIFunc('pncommerce', $newtype, 'newdata', array('property' => $newproperty));
        pnModAPIFunc('pncommerce', 'admin', 'propertyAdd', $newproperty);
        pnModAPIFunc('pncommerce', 'admin', 'recalculatepropertiessortorder', array('scheme_id' => $scheme_id));
    }
    pnRedirect(pnModURL('pncommerce', 'admin', 'editscheme', array('schemeid' => (int)$scheme_id)));
    return true;
}

/**
 * moveproperty
 *
 */
function pncommerce_admin_moveproperty()
{
    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN)) {
        return showerrorpage(_PNC_NOAUTH, __FILE__, __LINE__);
    }
    pncloadapi('admin', __FILE__, __LINE__);

    list($dir, $scheme_id, $property_id) = pnVarCleanFromInput('dir', 'scheme_id', 'property_id');
    $dir = strtolower($dir);
    if( ($dir<>'up' && $dir<>'down') || !isset($property_id) || !is_numeric($property_id) || !isset($scheme_id) || !is_numeric($scheme_id) ) {
        return showerrorpage(_MODARGSERROR, __FILE__, __LINE__);
    }

    $scheme = pnModAPIFunc('pncommerce', 'admin', 'schemeGet',
                           array('scheme_id' => $scheme_id));
// pncdebug('original', $scheme);
   for($cnt=0; $cnt<count($scheme['properties']); $cnt++) {
        if($scheme['properties'][$cnt]['property_id'] == $property_id) {
            if($dir=='up') {
                $scheme['properties'][$cnt]['sortorder'] = $scheme['properties'][$cnt]['sortorder'] - 3;
            } else {
                $scheme['properties'][$cnt]['sortorder'] = $scheme['properties'][$cnt]['sortorder'] + 3;
            }
            break;
        }
    }
//pncdebug('nach verschieben', $scheme);

    pnModAPIFunc('pncommerce', 'admin', 'storepropertiessortorder', array('properties' => $scheme['properties']));

    pnRedirect(pnModURL('pncommerce', 'admin', 'editscheme', array('schemeid' => $scheme_id)));
    return true;
}

?>
